<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>JSON::XS - JSON serialising/deserialising, done correctly and fast - metacpan.org</title>
        <link rel="preload" as="fetch" href="https://metacpan.org/account/login_status" crossorigin="anonymous" />
        <link href="https://metacpan.org/_assets/b8ccceeed47a0652049703d99326a9cea4933443.css" rel="stylesheet" type="text/css">
        <script src="https://metacpan.org/_assets/6bfedafe2d7caa915b7d84f61b45936818e3242e.js" type="text/javascript" defer></script>
        <link rel="alternate" type="application/rss+xml" title="Recent CPAN Uploads of JSON-XS - MetaCPAN" href="https://metacpan.org/dist/JSON-XS/releases.rss" />
        <link rel="canonical" href="./JSON::XS.html" />
        <meta name="description" content="JSON serialising/deserialising, done correctly and fast" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5">
        <link rel="shortcut icon" href="https://metacpan.org/static/icons/favicon.ico">
        <link rel="apple-touch-icon" sizes="152x152" href="https://metacpan.org/static/icons/apple-touch-icon.png">
        <link rel="search" href="https://metacpan.org/static/opensearch.xml" type="application/opensearchdescription+xml" title="MetaCPAN">
        <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

          (function(skey, ga_id){
            ga('create', ga_id, {
              siteSpeedSampleRate : 100,
              storage             : 'none',
              clientId            : localStorage.getItem(skey)
            });
            ga(function(tracker) {
              localStorage.setItem(skey, tracker.get('clientId'));
            });
            ga('send', 'pageview');
          })('ga:clientId', 'UA-27829474-1');
        </script>
<meta name="twitter:card"        content="summary" />
<meta name="twitter:url"         content="https://metacpan.org/pod/JSON::XS" />
<meta name="twitter:title"       content="JSON::XS" />
<meta name="twitter:description" content="JSON serialising/deserialising, done correctly and fast" />
<meta name="twitter:site"        content="metacpan" />
    </head>
    <body>
        <nav class="navbar navbar-default" role="navigation">
            <div class="header-logo-large hidden-xs">
              <a href="https://metacpan.org/" tabindex="0">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#logo" />
                </svg>
              </a>
            </div>
            <div class="header-logo-icon visible-xs">
              <a href="https://metacpan.org/">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#dots" />
                </svg>
              </a>
            </div>
            <ul class="nav navbar-nav menu-items hidden-xs hidden-sm">
              <li><a href="https://metacpan.org/about">About</a></li>
              <li><a href="https://metacpan.org/about/sponsors">Sponsor</a></li>
              <li><a href="https://grep.metacpan.org/">grep::cpan</a></li>
              <li><a href="https://metacpan.org/recent">Recent</a></li>
              <li><a href="https://metacpan.org/about/faq">FAQ</a></li>
              <li><a href="https://metacpan.org/tools">Tools</a></li>
              <li><a href="https://fastapi.metacpan.org/">API</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <button type="button" class="searchbar-btn visible-xs visible-sm">
                    <i class="fa fa-search button-fa-icon"></i>
                </button>
                <form action="https://metacpan.org/search" class="searchbar-form visible-md visible-lg search-form form-horizontal">
                   <input type="hidden" name="size" id="metacpan_search-size" value="20">
                  <div class="form-group">
                      <div class="search-group">
                        <i class="fa fa-search"></i>
                        <input type="text" name="q" placeholder="Search the CPAN" size="41" autocorrect="off" autocapitalize="off" spellcheck="false" id="metacpan_search-input" class="form-control" value="">
                      </div>
                  </div>
                </form>
                    <li class="icon-slidepanel visible-xs visible-sm">
                      <button data-toggle="slidepanel" data-target=".slidepanel">
                        <span class="button-fa-icon">
                          <i class="fa fa-bars slidepanel-open"></i>
                          <i class="fa fa-times slidepanel-close"></i>
                        </span>
                      </button>
                    </li>
                <form action="https://metacpan.org/account/logout" method="POST" id="metacpan-logout"></form>
                <li class="dropdown logged_in" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon logged-in-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a href="https://metacpan.org/account/identities">Identities</a></li>
                        <li><a href="https://metacpan.org/account/profile">Profile</a></li>
                        <li><a href="https://metacpan.org/account/favorite/list">Favorites</a></li>
                        <li>
                            <a href="./JSON::XS.html#" type="button" onclick="$('#metacpan-logout').submit(); return false">
                              Logout
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_out" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a href="https://metacpan.org/login/github">
                                <i class="fab fa-github fa-fw"></i>
                                GitHub
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/twitter">
                                <i class="fab fa-twitter fa-fw"></i>
                                Twitter
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/google">
                                <i class="fab fa-google fa-fw"></i>
                                Google
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_placeholder">
                    <button>
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                    </button>
                </li>
            </ul>
        </nav>
        <div class="page-content ">
          <!--
          <div class="top-notify-banner">
            <i class="fas fa-info-circle"></i>
          </div>
          -->
          <nav class="sidebar">
            <div class="slidepanel">
              <ul class="nav-list ">
    <li class="nav-header no-margin-top">
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The date that this version of JSON-XS was released.">
      <span class="relatize">27 Oct 2020 18:06:42 UTC</span>
    </li>
  <li>
    Distribution: <a href="https://metacpan.org/dist/JSON-XS">JSON-XS</a>
  </li>
  <li>
    Module version: 4.03
  </li>
  <li>
    <a data-keyboard-shortcut="g s" href="https://metacpan.org/dist/JSON-XS/source/XS.pm">Source</a>
    (<a href="https://metacpan.org/dist/JSON-XS/source/XS.pm?raw=1">raw</a>)
  </li>
  <li>
    <a data-keyboard-shortcut="g b" href="https://metacpan.org/dist/JSON-XS/source">Browse</a>
    (<a href="https://metacpan.org/dist/JSON-XS/source?raw=1">raw</a>)
  </li>
    <li>
      <a data-keyboard-shortcut="g c" href="https://metacpan.org/dist/JSON-XS/changes">Changes</a>
    </li>
    <li>
      <a class="nopopup" href="https://metacpan.org/dist/JSON-XS/contribute">How to Contribute</a>
    </li>
    <li>
      <a rel="noopener nofollow" data-keyboard-shortcut="g i" href="https://rt.cpan.org/Public/Dist/Display.html?Name=JSON-XS">Issues</a>
      (13)
    </li>
    <li>
      <a rel="noopener nofollow" href="http://matrix.cpantesters.org/?dist=JSON-XS+4.03" title="Matrix">Testers</a>
        <span title="(pass / fail / na)">(<a rel="noopener nofollow" href="https://www.cpantesters.org/distro/J/JSON-XS.html?oncpan=1&amp;distmat=1&amp;version=4.03&amp;grade=2" style="color: #090">5542</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/J/JSON-XS.html?oncpan=1&amp;distmat=1&amp;version=4.03&amp;grade=3" style="color: #900">410</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/J/JSON-XS.html?oncpan=1&amp;distmat=1&amp;version=4.03&amp;grade=4">0</a>)</span>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpants.cpanauthors.org/release/MLEHMANN/JSON-XS-4.03">Kwalitee</a>
    </li>
    <li>
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The # people with an indexing permission on JSON-XS who have released something to CPAN in the last 2 years (i.e. the # people likely able to release critical fixes in a timely manner)">
      Bus factor: 1
      </div>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpancover.com/latest/JSON-XS-4.03/index.html">82.13% Coverage </a>
    </li>
    <li>
      License: unknown
    </li>
    <li class="nav-header">Activity</li>
    <li>
<div class="activity-graph">
    <img src="https://metacpan.org/dist/JSON-XS/activity.svg?res=month" />
    <div class="comment">24 month</div>
</div>
    </li>
    <li class="nav-header">Tools</li>
    <li>
      <a itemprop="downloadUrl" href="https://cpan.metacpan.org/authors/id/M/ML/MLEHMANN/JSON-XS-4.03.tar.gz">
      Download (<span itemprop="fileSize">84.72KB</span>)</a>
    </li>
    <li>
      <a href="https://explorer.metacpan.org/?url=%2Fmodule%2FMLEHMANN%2FJSON-XS-4.03%2FXS.pm">
        MetaCPAN Explorer
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/JSON-XS/permissions">
        Permissions
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/JSON-XS/releases.rss">
        Subscribe to distribution
      </a>
    </li>
    <li>
      <button class="btn btn-link" data-toggle="modal" data-target="#metacpan_install-instructions-dialog">
        Install Instructions
      </button>
    </li>
    <li>
      <form action="https://metacpan.org/search">
        <input type="hidden" name="q" value="dist:JSON-XS">
        <input type="search" name="q" placeholder="Search distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
      </form>
    </li>
    <li>
      <form action="https://grep.metacpan.org/search">
        <input type="hidden" name="qd" value="JSON-XS">
        <input type="hidden" name="source" value="metacpan">
        <input type="search" name="q" placeholder="grep distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
     </form>
    </li>
    <li class="version-jump">
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/XS.pm&#39;" class="form-control tool-bar-form">
  <option disabled selected>Jump to version</option>
<option
  disabled
  value="MLEHMANN/JSON-XS-4.03"
>4.03
  (MLEHMANN on 2020-10-27)</option>
<optgroup label="BackPAN">'
<option
  
  value="MLEHMANN/JSON-XS-4.02"
>4.02
  (MLEHMANN on 2019-03-06)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.01"
>4.01
  (MLEHMANN on 2019-02-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.0"
>4.0
  (MLEHMANN on 2018-11-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.0_00"
>4.0_00 DEV
  (MLEHMANN on 2018-11-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.04"
>3.04
  (MLEHMANN on 2017-08-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.03"
>3.03
  (MLEHMANN on 2016-11-16)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.02"
>3.02
  (MLEHMANN on 2016-02-26)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.01"
>3.01
  (MLEHMANN on 2013-10-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.0"
>3.0
  (MLEHMANN on 2013-10-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.34"
>2.34
  (MLEHMANN on 2013-05-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.33"
>2.33
  (MLEHMANN on 2012-08-01)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.32"
>2.32
  (MLEHMANN on 2011-08-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.31"
>2.31
  (MLEHMANN on 2011-07-27)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.3"
>2.3
  (MLEHMANN on 2010-08-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.29"
>2.29
  (MLEHMANN on 2010-03-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.28"
>2.28
  (MLEHMANN on 2010-03-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.27"
>2.27
  (MLEHMANN on 2010-01-07)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.26"
>2.26
  (MLEHMANN on 2009-10-10)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.25"
>2.25
  (MLEHMANN on 2009-08-08)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.24"
>2.24
  (MLEHMANN on 2009-05-30)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.232"
>2.232
  (MLEHMANN on 2009-02-22)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2311"
>2.2311
  (MLEHMANN on 2009-02-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.231"
>2.231
  (MLEHMANN on 2008-11-20)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.23"
>2.23
  (MLEHMANN on 2008-09-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2222"
>2.2222
  (MLEHMANN on 2008-07-20)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.222"
>2.222
  (MLEHMANN on 2008-07-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.22"
>2.22
  (MLEHMANN on 2008-07-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.21"
>2.21
  (MLEHMANN on 2008-06-03)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2"
>2.2
  (MLEHMANN on 2008-04-16)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.1"
>2.1
  (MLEHMANN on 2008-03-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.01"
>2.01
  (MLEHMANN on 2007-12-05)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.0"
>2.0
  (MLEHMANN on 2007-12-04)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.53"
>1.53
  (MLEHMANN on 2007-11-13)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.52"
>1.52
  (MLEHMANN on 2007-10-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.51"
>1.51
  (MLEHMANN on 2007-10-13)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.5"
>1.5
  (MLEHMANN on 2007-08-28)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.44"
>1.44
  (MLEHMANN on 2007-08-21)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.43"
>1.43
  (MLEHMANN on 2007-07-26)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.42"
>1.42
  (MLEHMANN on 2007-07-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.41"
>1.41
  (MLEHMANN on 2007-07-10)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.4"
>1.4
  (MLEHMANN on 2007-07-02)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.3"
>1.3
  (MLEHMANN on 2007-06-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.24"
>1.24
  (MLEHMANN on 2007-06-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.23"
>1.23
  (MLEHMANN on 2007-06-06)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.22"
>1.22
  (MLEHMANN on 2007-05-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.21"
>1.21
  (MLEHMANN on 2007-05-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.2"
>1.2
  (MLEHMANN on 2007-05-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.11"
>1.11
  (MLEHMANN on 2007-04-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.1"
>1.1
  (MLEHMANN on 2007-04-04)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.01"
>1.01
  (MLEHMANN on 2007-03-31)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.0"
>1.0
  (MLEHMANN on 2007-03-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.8"
>0.8
  (MLEHMANN on 2007-03-25)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.7"
>0.7
  (MLEHMANN on 2007-03-25)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.5"
>0.5
  (MLEHMANN on 2007-03-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.31"
>0.31
  (MLEHMANN on 2007-03-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.3"
>0.3
  (MLEHMANN on 2007-03-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.2"
>0.2
  (MLEHMANN on 2007-03-22)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.1"
>0.1
  (MLEHMANN on 2007-03-22)</option>
</optgroup>
</select>
    </li>
    <li class="version-diff">
<select onchange="document.location.href='/release/MLEHMANN/JSON-XS-4.03/diff/' + encodeURIComponent(this.value) + '/XS.pm'
" class="form-control tool-bar-form">
  <option disabled selected>Diff with version</option>
<option
  disabled
  value="MLEHMANN/JSON-XS-4.03"
>4.03
  (MLEHMANN on 2020-10-27)</option>
<optgroup label="BackPAN">'
<option
  
  value="MLEHMANN/JSON-XS-4.02"
>4.02
  (MLEHMANN on 2019-03-06)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.01"
>4.01
  (MLEHMANN on 2019-02-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.0"
>4.0
  (MLEHMANN on 2018-11-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.0_00"
>4.0_00 DEV
  (MLEHMANN on 2018-11-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.04"
>3.04
  (MLEHMANN on 2017-08-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.03"
>3.03
  (MLEHMANN on 2016-11-16)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.02"
>3.02
  (MLEHMANN on 2016-02-26)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.01"
>3.01
  (MLEHMANN on 2013-10-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.0"
>3.0
  (MLEHMANN on 2013-10-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.34"
>2.34
  (MLEHMANN on 2013-05-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.33"
>2.33
  (MLEHMANN on 2012-08-01)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.32"
>2.32
  (MLEHMANN on 2011-08-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.31"
>2.31
  (MLEHMANN on 2011-07-27)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.3"
>2.3
  (MLEHMANN on 2010-08-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.29"
>2.29
  (MLEHMANN on 2010-03-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.28"
>2.28
  (MLEHMANN on 2010-03-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.27"
>2.27
  (MLEHMANN on 2010-01-07)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.26"
>2.26
  (MLEHMANN on 2009-10-10)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.25"
>2.25
  (MLEHMANN on 2009-08-08)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.24"
>2.24
  (MLEHMANN on 2009-05-30)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.232"
>2.232
  (MLEHMANN on 2009-02-22)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2311"
>2.2311
  (MLEHMANN on 2009-02-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.231"
>2.231
  (MLEHMANN on 2008-11-20)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.23"
>2.23
  (MLEHMANN on 2008-09-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2222"
>2.2222
  (MLEHMANN on 2008-07-20)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.222"
>2.222
  (MLEHMANN on 2008-07-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.22"
>2.22
  (MLEHMANN on 2008-07-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.21"
>2.21
  (MLEHMANN on 2008-06-03)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2"
>2.2
  (MLEHMANN on 2008-04-16)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.1"
>2.1
  (MLEHMANN on 2008-03-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.01"
>2.01
  (MLEHMANN on 2007-12-05)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.0"
>2.0
  (MLEHMANN on 2007-12-04)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.53"
>1.53
  (MLEHMANN on 2007-11-13)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.52"
>1.52
  (MLEHMANN on 2007-10-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.51"
>1.51
  (MLEHMANN on 2007-10-13)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.5"
>1.5
  (MLEHMANN on 2007-08-28)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.44"
>1.44
  (MLEHMANN on 2007-08-21)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.43"
>1.43
  (MLEHMANN on 2007-07-26)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.42"
>1.42
  (MLEHMANN on 2007-07-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.41"
>1.41
  (MLEHMANN on 2007-07-10)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.4"
>1.4
  (MLEHMANN on 2007-07-02)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.3"
>1.3
  (MLEHMANN on 2007-06-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.24"
>1.24
  (MLEHMANN on 2007-06-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.23"
>1.23
  (MLEHMANN on 2007-06-06)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.22"
>1.22
  (MLEHMANN on 2007-05-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.21"
>1.21
  (MLEHMANN on 2007-05-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.2"
>1.2
  (MLEHMANN on 2007-05-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.11"
>1.11
  (MLEHMANN on 2007-04-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.1"
>1.1
  (MLEHMANN on 2007-04-04)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.01"
>1.01
  (MLEHMANN on 2007-03-31)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.0"
>1.0
  (MLEHMANN on 2007-03-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.8"
>0.8
  (MLEHMANN on 2007-03-25)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.7"
>0.7
  (MLEHMANN on 2007-03-25)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.5"
>0.5
  (MLEHMANN on 2007-03-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.31"
>0.31
  (MLEHMANN on 2007-03-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.3"
>0.3
  (MLEHMANN on 2007-03-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.2"
>0.2
  (MLEHMANN on 2007-03-22)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.1"
>0.1
  (MLEHMANN on 2007-03-22)</option>
</optgroup>
</select>
    </li>

    <li>
<ul class="dependencies">
  <li class="nav-header">Dependencies</li>
  <li><a href="https://metacpan.org/pod/Types::Serialiser" title="Types::Serialiser" class="ellipsis">Types::Serialiser</a></li>
  <li><a href="https://metacpan.org/pod/common::sense" title="common::sense" class="ellipsis">common::sense</a></li>
  <li><i class="ttip" title="dynamic_config enabled">and possibly others</i></li>
  <li>
    <hr>
  </li>
  <li>
    <a href="https://metacpan.org/module/JSON::XS/requires">Reverse dependencies</a>
  </li>
  <li>
    <a href="http://deps.cpantesters.org/?module=JSON%3A%3AXS">CPAN Testers List</a>
  </li>
  <li>
    <a href="https://cpandeps.grinnz.com/?dist=JSON-XS">Dependency graph</a>
  </li>
</ul>
    </li>
    <li class="nav-header">Permalinks</li>
    <li>
      <a href="https://metacpan.org/release/MLEHMANN/JSON-XS-4.03/view/XS.pm">This version</a>
    </li>
    <li>
      <a href="./JSON::XS.html">Latest version</a>
    </li>
    <li>
<div class="plussers">
<div class="nav-header">++ed by:</div>
<div>
<a class="display-all" href="https://metacpan.org/author/DCPETROV"><img src="https://www.gravatar.com/avatar/10e265a667839a004d83dd3ed6b6cfc9?d=identicon&amp;s=20" title="DCPETROV" alt="DCPETROV"></a>
<a class="display-all" href="https://metacpan.org/author/TOKUHIROM"><img src="https://www.gravatar.com/avatar/70f90c6a0bcd84348b02309babc98684?d=identicon&amp;s=20" title="TOKUHIROM" alt="TOKUHIROM"></a>
<a class="display-all" href="https://metacpan.org/author/PLU"><img src="https://www.gravatar.com/avatar/b4db07dda59c4fcacce75e943ff4cbb7?d=identicon&amp;s=20" title="PLU" alt="PLU"></a>
<a class="display-all" href="https://metacpan.org/author/FLORIAN"><img src="https://www.gravatar.com/avatar/1048685443f8ea1d6024daa5cac92e9a?d=identicon&amp;s=20" title="FLORIAN" alt="FLORIAN"></a>
<a class="display-all" href="https://metacpan.org/author/GETTY"><img src="https://www.gravatar.com/avatar/d374f794bb2f39232c29d0b376b9dcc4?d=identicon&amp;s=20" title="GETTY" alt="GETTY"></a>
</div>
<!-- Display counts of plussers-->
<div>
    <a href="https://metacpan.org/dist/JSON-XS/plussers">66 PAUSE users</a>
</div>
<div>
    51 non-PAUSE users
</div>
</div>
    </li>
    <li>
    </li>
              </ul>
            </div>
          </nav>
          <div class="content-navigation">
<div class="breadcrumbs">
  <span>
    <a data-keyboard-shortcut="g a" rel="author" href="https://metacpan.org/author/MLEHMANN" class="author-name">Marc A. Lehmann</a>
  </span>
  <span>&nbsp;/&nbsp;</span>
  <div class="release dist-release status-latest maturity-released">
    <span class="dropdown"><b class="caret"></b></span>
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/XS.pm&#39;" class="">
<option
  selected
  value="MLEHMANN/JSON-XS-4.03"
>4.03
  (MLEHMANN on 2020-10-27)</option>
<optgroup label="BackPAN">'
<option
  
  value="MLEHMANN/JSON-XS-4.02"
>4.02
  (MLEHMANN on 2019-03-06)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.01"
>4.01
  (MLEHMANN on 2019-02-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.0"
>4.0
  (MLEHMANN on 2018-11-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-4.0_00"
>4.0_00 DEV
  (MLEHMANN on 2018-11-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.04"
>3.04
  (MLEHMANN on 2017-08-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.03"
>3.03
  (MLEHMANN on 2016-11-16)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.02"
>3.02
  (MLEHMANN on 2016-02-26)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.01"
>3.01
  (MLEHMANN on 2013-10-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-3.0"
>3.0
  (MLEHMANN on 2013-10-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.34"
>2.34
  (MLEHMANN on 2013-05-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.33"
>2.33
  (MLEHMANN on 2012-08-01)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.32"
>2.32
  (MLEHMANN on 2011-08-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.31"
>2.31
  (MLEHMANN on 2011-07-27)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.3"
>2.3
  (MLEHMANN on 2010-08-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.29"
>2.29
  (MLEHMANN on 2010-03-17)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.28"
>2.28
  (MLEHMANN on 2010-03-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.27"
>2.27
  (MLEHMANN on 2010-01-07)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.26"
>2.26
  (MLEHMANN on 2009-10-10)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.25"
>2.25
  (MLEHMANN on 2009-08-08)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.24"
>2.24
  (MLEHMANN on 2009-05-30)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.232"
>2.232
  (MLEHMANN on 2009-02-22)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2311"
>2.2311
  (MLEHMANN on 2009-02-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.231"
>2.231
  (MLEHMANN on 2008-11-20)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.23"
>2.23
  (MLEHMANN on 2008-09-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2222"
>2.2222
  (MLEHMANN on 2008-07-20)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.222"
>2.222
  (MLEHMANN on 2008-07-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.22"
>2.22
  (MLEHMANN on 2008-07-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.21"
>2.21
  (MLEHMANN on 2008-06-03)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.2"
>2.2
  (MLEHMANN on 2008-04-16)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.1"
>2.1
  (MLEHMANN on 2008-03-19)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.01"
>2.01
  (MLEHMANN on 2007-12-05)</option>
<option
  
  value="MLEHMANN/JSON-XS-2.0"
>2.0
  (MLEHMANN on 2007-12-04)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.53"
>1.53
  (MLEHMANN on 2007-11-13)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.52"
>1.52
  (MLEHMANN on 2007-10-15)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.51"
>1.51
  (MLEHMANN on 2007-10-13)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.5"
>1.5
  (MLEHMANN on 2007-08-28)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.44"
>1.44
  (MLEHMANN on 2007-08-21)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.43"
>1.43
  (MLEHMANN on 2007-07-26)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.42"
>1.42
  (MLEHMANN on 2007-07-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.41"
>1.41
  (MLEHMANN on 2007-07-10)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.4"
>1.4
  (MLEHMANN on 2007-07-02)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.3"
>1.3
  (MLEHMANN on 2007-06-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.24"
>1.24
  (MLEHMANN on 2007-06-11)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.23"
>1.23
  (MLEHMANN on 2007-06-06)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.22"
>1.22
  (MLEHMANN on 2007-05-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.21"
>1.21
  (MLEHMANN on 2007-05-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.2"
>1.2
  (MLEHMANN on 2007-05-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.11"
>1.11
  (MLEHMANN on 2007-04-09)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.1"
>1.1
  (MLEHMANN on 2007-04-04)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.01"
>1.01
  (MLEHMANN on 2007-03-31)</option>
<option
  
  value="MLEHMANN/JSON-XS-1.0"
>1.0
  (MLEHMANN on 2007-03-29)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.8"
>0.8
  (MLEHMANN on 2007-03-25)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.7"
>0.7
  (MLEHMANN on 2007-03-25)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.5"
>0.5
  (MLEHMANN on 2007-03-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.31"
>0.31
  (MLEHMANN on 2007-03-24)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.3"
>0.3
  (MLEHMANN on 2007-03-23)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.2"
>0.2
  (MLEHMANN on 2007-03-22)</option>
<option
  
  value="MLEHMANN/JSON-XS-0.1"
>0.1
  (MLEHMANN on 2007-03-22)</option>
</optgroup>
</select>
    <a data-keyboard-shortcut="g d" class="release-name" href="https://metacpan.org/dist/JSON-XS">JSON-XS-4.03</a>
  </div>
<span class="river-gauge-gauge">
  <svg width="24px"
       height="15px"
       version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink">

    <g>
      <title>        River stage three &#10;
          • 461 direct dependents &#10;          • 797 total dependents
      </title>

      <rect x="0"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="5"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="10"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="15"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="20"  y="0" width="4" height="15" fill="#e4e2e2" />
    </g>
  </svg>

</span>
<div id="JSON-XS-fav" class="logged_in">
<form action="https://metacpan.org/account/favorite/add" style="display: inline" onsubmit="return favDistribution(this)">
    <input type="hidden" name="remove" value="0">
    <input type="hidden" name="release" value="JSON-XS-4.03">
    <input type="hidden" name="author" value="MLEHMANN">
    <input type="hidden" name="distribution" value="JSON-XS">
    <button type="submit" class="favorite highlight"><span>117</span> ++</button>
</form>
</div>
<div class="logged_out">
<a href="./JSON::XS.html" onclick="alert('Please sign in to add favorites'); return false" class="favorite highlight">
<span>117</span> ++</a>
</div>
   / <span>JSON::XS</span>
</div>
          </div>
          <main class="content">


<nav class="toc">
  <div class="toc-header"><strong>Contents</strong></div>
<ul>
  <li><a href="./JSON::XS.html#NAME">NAME</a></li>
  <li><a href="./JSON::XS.html#SYNOPSIS">SYNOPSIS</a></li>
  <li><a href="./JSON::XS.html#DESCRIPTION">DESCRIPTION</a>
    <ul>
      <li><a href="./JSON::XS.html#FEATURES">FEATURES</a></li>
    </ul>
  </li>
  <li><a href="./JSON::XS.html#FUNCTIONAL-INTERFACE">FUNCTIONAL INTERFACE</a></li>
  <li><a href="./JSON::XS.html#A-FEW-NOTES-ON-UNICODE-AND-PERL">A FEW NOTES ON UNICODE AND PERL</a></li>
  <li><a href="./JSON::XS.html#OBJECT-ORIENTED-INTERFACE">OBJECT-ORIENTED INTERFACE</a></li>
  <li><a href="./JSON::XS.html#INCREMENTAL-PARSING">INCREMENTAL PARSING</a>
    <ul>
      <li><a href="./JSON::XS.html#LIMITATIONS">LIMITATIONS</a></li>
      <li><a href="./JSON::XS.html#EXAMPLES">EXAMPLES</a></li>
    </ul>
  </li>
  <li><a href="./JSON::XS.html#MAPPING">MAPPING</a>
    <ul>
      <li><a href="./JSON::XS.html#JSON-%3E-PERL">JSON -&gt; PERL</a></li>
      <li><a href="./JSON::XS.html#PERL-%3E-JSON">PERL -&gt; JSON</a></li>
      <li><a href="./JSON::XS.html#OBJECT-SERIALISATION">OBJECT SERIALISATION</a>
        <ul>
          <li><a href="./JSON::XS.html#SERIALISATION">SERIALISATION</a></li>
          <li><a href="./JSON::XS.html#DESERIALISATION">DESERIALISATION</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="./JSON::XS.html#ENCODING/CODESET-FLAG-NOTES">ENCODING/CODESET FLAG NOTES</a>
    <ul>
      <li><a href="./JSON::XS.html#JSON-and-ECMAscript">JSON and ECMAscript</a></li>
      <li><a href="./JSON::XS.html#JSON-and-YAML">JSON and YAML</a></li>
      <li><a href="./JSON::XS.html#SPEED">SPEED</a></li>
    </ul>
  </li>
  <li><a href="./JSON::XS.html#SECURITY-CONSIDERATIONS">SECURITY CONSIDERATIONS</a>
    <ul>
      <li><a href="./JSON::XS.html#%22OLD%22-VS.-%22NEW%22-JSON-(RFC4627-VS.-RFC7159)">&quot;OLD&quot; VS. &quot;NEW&quot; JSON (RFC4627 VS. RFC7159)</a></li>
    </ul>
  </li>
  <li><a href="./JSON::XS.html#RELATIONSHIP-WITH-I-JSON">RELATIONSHIP WITH I-JSON</a></li>
  <li><a href="./JSON::XS.html#INTEROPERABILITY-WITH-OTHER-MODULES">INTEROPERABILITY WITH OTHER MODULES</a></li>
  <li><a href="./JSON::XS.html#INTEROPERABILITY-WITH-OTHER-JSON-DECODERS">INTEROPERABILITY WITH OTHER JSON DECODERS</a>
    <ul>
      <li><a href="./JSON::XS.html#TAGGED-VALUE-SYNTAX-AND-STANDARD-JSON-EN/DECODERS">TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS</a></li>
    </ul>
  </li>
  <li><a href="./JSON::XS.html#(I-)THREADS">(I-)THREADS</a></li>
  <li><a href="./JSON::XS.html#THE-PERILS-OF-SETLOCALE">THE PERILS OF SETLOCALE</a></li>
  <li><a href="./JSON::XS.html#SOME-HISTORY">SOME HISTORY</a></li>
  <li><a href="./JSON::XS.html#BUGS">BUGS</a></li>
  <li><a href="./JSON::XS.html#SEE-ALSO">SEE ALSO</a></li>
  <li><a href="./JSON::XS.html#AUTHOR">AUTHOR</a></li>
</ul></nav>
<div class="pod anchors">
<h1 id="NAME">NAME</h1>

<p>JSON::XS - JSON serialising/deserialising, done correctly and fast</p>

<p>JSON::XS - &#x6B63;&#x3057;&#x304F;&#x3066;&#x9AD8;&#x901F;&#x306A; JSON &#x30B7;&#x30EA;&#x30A2;&#x30E9;&#x30A4;&#x30B6;/&#x30C7;&#x30B7;&#x30EA;&#x30A2;&#x30E9;&#x30A4;&#x30B6; (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html)</p>

<h1 id="SYNOPSIS">SYNOPSIS</h1>

<pre><code> use JSON::XS;

 # exported functions, they croak on error
 # and expect/generate UTF-8

 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
 $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;

 # OO-interface

 $coder = JSON::XS-&gt;new-&gt;ascii-&gt;pretty-&gt;allow_nonref;
 $pretty_printed_unencoded = $coder-&gt;encode ($perl_scalar);
 $perl_scalar = $coder-&gt;decode ($unicode_json_text);

 # Note that JSON version 2.0 and above will automatically use JSON::XS
 # if available, at virtually no speed overhead either, so you should
 # be able to just:
 
 use JSON;

 # and do the same things, except that you have a pure-perl fallback now.</code></pre>

<h1 id="DESCRIPTION">DESCRIPTION</h1>

<p>This module converts Perl data structures to JSON and vice versa. Its primary goal is to be <i>correct</i> and its secondary goal is to be <i>fast</i>. To reach the latter goal it was written in C.</p>

<p>See MAPPING, below, on how JSON::XS maps perl values to JSON values and vice versa.</p>

<h2 id="FEATURES">FEATURES</h2>

<ul>

<li><p>correct Unicode handling</p>

<p>This module knows how to handle Unicode, documents how and when it does so, and even documents what &quot;correct&quot; means.</p>

</li>
<li><p>round-trip integrity</p>

<p>When you serialise a perl data structure using only data types supported by JSON and Perl, the deserialised data structure is identical on the Perl level. (e.g. the string &quot;2.0&quot; doesn&#39;t suddenly become &quot;2&quot; just because it looks like a number). There <i>are</i> minor exceptions to this, read the MAPPING section below to learn about those.</p>

</li>
<li><p>strict checking of JSON correctness</p>

<p>There is no guessing, no generating of illegal JSON texts by default, and only JSON is accepted as input by default (the latter is a security feature).</p>

</li>
<li><p>fast</p>

<p>Compared to other JSON modules and other serialisers such as Storable, this module usually compares favourably in terms of speed, too.</p>

</li>
<li><p>simple to use</p>

<p>This module has both a simple functional interface as well as an object oriented interface.</p>

</li>
<li><p>reasonably versatile output formats</p>

<p>You can choose between the most compact guaranteed-single-line format possible (nice for simple line-based protocols), a pure-ASCII format (for when your transport is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed format (for when you want to read that stuff). Or you can combine those features in whatever way you like.</p>

</li>
</ul>

<h1 id="FUNCTIONAL-INTERFACE"><a id="FUNCTIONAL"></a>FUNCTIONAL INTERFACE</h1>

<p>The following convenience methods are provided by this module. They are exported by default:</p>

<dl>

<dt id="$json_text-=-encode_json-$perl_scalar"><a id="json_text---encode_json--perl_scalar"></a>$json_text = encode_json $perl_scalar</dt>
<dd>

<p>Converts the given Perl data structure to a UTF-8 encoded, binary string (that is, the string contains octets only). Croaks on error.</p>

<p>This function call is functionally identical to:</p>

<pre><code>   $json_text = JSON::XS-&gt;new-&gt;utf8-&gt;encode ($perl_scalar)</code></pre>

<p>Except being faster.</p>

</dd>
<dt id="$perl_scalar-=-decode_json-$json_text"><a id="perl_scalar---decode_json--json_text"></a>$perl_scalar = decode_json $json_text</dt>
<dd>

<p>The opposite of <code>encode_json</code>: expects a UTF-8 (binary) string and tries to parse that as a UTF-8 encoded JSON text, returning the resulting reference. Croaks on error.</p>

<p>This function call is functionally identical to:</p>

<pre><code>   $perl_scalar = JSON::XS-&gt;new-&gt;utf8-&gt;decode ($json_text)</code></pre>

<p>Except being faster.</p>

</dd>
</dl>

<h1 id="A-FEW-NOTES-ON-UNICODE-AND-PERL"><a id="A"></a>A FEW NOTES ON UNICODE AND PERL</h1>

<p>Since this often leads to confusion, here are a few very clear words on how Unicode works in Perl, modulo bugs.</p>

<dl>

<dt id="1.-Perl-strings-can-store-characters-with-ordinal-values-&gt;-255."><a id="1"></a><a id="Perl-strings-can-store-characters-with-ordinal-values---255"></a>1. Perl strings can store characters with ordinal values &gt; 255.</dt>
<dd>

<p>This enables you to store Unicode characters as single characters in a Perl string - very natural.</p>

</dd>
<dt id="2.-Perl-does-not-associate-an-encoding-with-your-strings."><a id="2"></a><a id="Perl-does-not-associate-an-encoding-with-your-strings"></a>2. Perl does <i>not</i> associate an encoding with your strings.</dt>
<dd>

<p>... until you force it to, e.g. when matching it against a regex, or printing the scalar to a file, in which case Perl either interprets your string as locale-encoded text, octets/binary, or as Unicode, depending on various settings. In no case is an encoding stored together with your data, it is <i>use</i> that decides encoding, not any magical meta data.</p>

</dd>
<dt id="3.-The-internal-utf-8-flag-has-no-meaning-with-regards-to-the-encoding-of-your-string."><a id="3"></a><a id="The-internal-utf-8-flag-has-no-meaning-with-regards-to-the-encoding-of-your-string"></a>3. The internal utf-8 flag has no meaning with regards to the encoding of your string.</dt>
<dd>

<p>Just ignore that flag unless you debug a Perl bug, a module written in XS or want to dive into the internals of perl. Otherwise it will only confuse you, as, despite the name, it says nothing about how your string is encoded. You can have Unicode strings with that flag set, with that flag clear, and you can have binary data with that flag set and that flag clear. Other possibilities exist, too.</p>

<p>If you didn&#39;t know about that flag, just the better, pretend it doesn&#39;t exist.</p>

</dd>
<dt id="4.-A-&quot;Unicode-String&quot;-is-simply-a-string-where-each-character-can-be-validly-interpreted-as-a-Unicode-code-point."><a id="4"></a><a id="A--Unicode-String--is-simply-a-string-where-each-character-can-be-validly-interpreted-as-a-Unicode-code-point"></a>4. A &quot;Unicode String&quot; is simply a string where each character can be validly interpreted as a Unicode code point.</dt>
<dd>

<p>If you have UTF-8 encoded data, it is no longer a Unicode string, but a Unicode string encoded in UTF-8, giving you a binary string.</p>

</dd>
<dt id="5.-A-string-containing-&quot;high&quot;-(&gt;-255)-character-values-is-not-a-UTF-8-string."><a id="5"></a><a id="A-string-containing--high----255--character-values-is-not-a-UTF-8-string"></a>5. A string containing &quot;high&quot; (&gt; 255) character values is <i>not</i> a UTF-8 string.</dt>
<dd>

<p>It&#39;s a fact. Learn to live with it.</p>

</dd>
</dl>

<p>I hope this helps :)</p>

<h1 id="OBJECT-ORIENTED-INTERFACE"><a id="OBJECT"></a>OBJECT-ORIENTED INTERFACE</h1>

<p>The object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats.</p>

<dl>

<dt id="$json-=-new-JSON::XS"><a id="json---new-JSON::XS"></a>$json = new JSON::XS</dt>
<dd>

<p>Creates a new JSON::XS object that can be used to de/encode JSON strings. All boolean flags described below are by default <i>disabled</i> (with the exception of <code>allow_nonref</code>, which defaults to <i>enabled</i> since version <code>4.0</code>).</p>

<p>The mutators for flags all return the JSON object again and thus calls can be chained:</p>

<pre><code>   my $json = JSON::XS-&gt;new-&gt;utf8-&gt;space_after-&gt;encode ({a =&gt; [1,2]})
   =&gt; {&quot;a&quot;: [1, 2]}</code></pre>

</dd>
<dt id="$json-=-$json-&gt;ascii-([$enable])"><a id="json----json--ascii--enable"></a>$json = $json-&gt;ascii ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_ascii"><a id="enabled----json--get_ascii"></a>$enabled = $json-&gt;get_ascii</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will not generate characters outside the code range <code>0..127</code> (which is ASCII). Any Unicode characters outside that range will be escaped using either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. The resulting encoded JSON text can be treated as a native Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, or any other superset of ASCII.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format.</p>

<p>See also the section <i>ENCODING/CODESET FLAG NOTES</i> later in this document.</p>

<p>The main use for this flag is to produce JSON texts that can be transmitted over a 7-bit channel, as the encoded JSON texts will not contain any 8 bit characters.</p>

<pre><code>  JSON::XS-&gt;new-&gt;ascii (1)-&gt;encode ([chr 0x10401])
  =&gt; [&quot;\ud801\udc01&quot;]</code></pre>

</dd>
<dt id="$json-=-$json-&gt;latin1-([$enable])"><a id="json----json--latin1--enable"></a>$json = $json-&gt;latin1 ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_latin1"><a id="enabled----json--get_latin1"></a>$enabled = $json-&gt;get_latin1</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will encode the resulting JSON text as latin1 (or iso-8859-1), escaping any characters outside the code range <code>0..255</code>. The resulting string can be treated as a latin1-encoded JSON text or a native Unicode string. The <code>decode</code> method will not be affected in any way by this flag, as <code>decode</code> by default expects Unicode, which is a strict superset of latin1.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will not escape Unicode characters unless required by the JSON syntax or other flags.</p>

<p>See also the section <i>ENCODING/CODESET FLAG NOTES</i> later in this document.</p>

<p>The main use for this flag is efficiently encoding binary data as JSON text, as most octets will not be escaped, resulting in a smaller encoded size. The disadvantage is that the resulting JSON text is encoded in latin1 (and must correctly be treated as such when storing and transferring), a rare encoding for JSON. It is therefore most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when talking to other JSON encoders/decoders.</p>

<pre><code>  JSON::XS-&gt;new-&gt;latin1-&gt;encode ([&quot;\x{89}\x{abc}&quot;]
  =&gt; [&quot;\x{89}\\u0abc&quot;]    # (perl syntax, U+abc escaped, U+89 not)</code></pre>

</dd>
<dt id="$json-=-$json-&gt;utf8-([$enable])"><a id="json----json--utf8--enable"></a>$json = $json-&gt;utf8 ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_utf8"><a id="enabled----json--get_utf8"></a>$enabled = $json-&gt;get_utf8</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will encode the JSON result into UTF-8, as required by many protocols, while the <code>decode</code> method expects to be handed a UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range <code>0..255</code>, they are thus useful for bytewise/binary I/O. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will return the JSON string as a (non-encoded) Unicode string, while <code>decode</code> expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.</p>

<p>See also the section <i>ENCODING/CODESET FLAG NOTES</i> later in this document.</p>

<p>Example, output UTF-16BE-encoded JSON:</p>

<pre><code>  use Encode;
  $jsontext = encode &quot;UTF-16BE&quot;, JSON::XS-&gt;new-&gt;encode ($object);</code></pre>

<p>Example, decode UTF-32LE-encoded JSON:</p>

<pre><code>  use Encode;
  $object = JSON::XS-&gt;new-&gt;decode (decode &quot;UTF-32LE&quot;, $jsontext);</code></pre>

</dd>
<dt id="$json-=-$json-&gt;pretty-([$enable])"><a id="json----json--pretty--enable"></a>$json = $json-&gt;pretty ([$enable])</dt>
<dd>

<p>This enables (or disables) all of the <code>indent</code>, <code>space_before</code> and <code>space_after</code> (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible.</p>

<p>Example, pretty-print some simple structure:</p>

<pre><code>   my $json = JSON::XS-&gt;new-&gt;pretty(1)-&gt;encode ({a =&gt; [1,2]})
   =&gt;
   {
      &quot;a&quot; : [
         1,
         2
      ]
   }</code></pre>

</dd>
<dt id="$json-=-$json-&gt;indent-([$enable])"><a id="json----json--indent--enable"></a>$json = $json-&gt;indent ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_indent"><a id="enabled----json--get_indent"></a>$enabled = $json-&gt;get_indent</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly.</p>

<p>If <code>$enable</code> is false, no newlines or indenting will be produced, and the resulting JSON text is guaranteed not to contain any <code>newlines</code>.</p>

<p>This setting has no effect when decoding JSON texts.</p>

</dd>
<dt id="$json-=-$json-&gt;space_before-([$enable])"><a id="json----json--space_before--enable"></a>$json = $json-&gt;space_before ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_space_before"><a id="enabled----json--get_space_before"></a>$enabled = $json-&gt;get_space_before</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will add an extra optional space before the <code>:</code> separating keys from values in JSON objects.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will not add any extra space at those places.</p>

<p>This setting has no effect when decoding JSON texts. You will also most likely combine this setting with <code>space_after</code>.</p>

<p>Example, space_before enabled, space_after and indent disabled:</p>

<pre><code>   {&quot;key&quot; :&quot;value&quot;}</code></pre>

</dd>
<dt id="$json-=-$json-&gt;space_after-([$enable])"><a id="json----json--space_after--enable"></a>$json = $json-&gt;space_after ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_space_after"><a id="enabled----json--get_space_after"></a>$enabled = $json-&gt;get_space_after</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will add an extra optional space after the <code>:</code> separating keys from values in JSON objects and extra whitespace after the <code>,</code> separating key-value pairs and array members.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will not add any extra space at those places.</p>

<p>This setting has no effect when decoding JSON texts.</p>

<p>Example, space_before and indent disabled, space_after enabled:</p>

<pre><code>   {&quot;key&quot;: &quot;value&quot;}</code></pre>

</dd>
<dt id="$json-=-$json-&gt;relaxed-([$enable])"><a id="json----json--relaxed--enable"></a>$json = $json-&gt;relaxed ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_relaxed"><a id="enabled----json--get_relaxed"></a>$enabled = $json-&gt;get_relaxed</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then <code>decode</code> will accept some extensions to normal JSON syntax (see below). <code>encode</code> will not be affected in any way. <i>Be aware that this option makes you accept invalid JSON texts as if they were valid!</i>. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)</p>

<p>If <code>$enable</code> is false (the default), then <code>decode</code> will only accept valid JSON texts.</p>

<p>Currently accepted extensions are:</p>

<ul>

<li><p>list items can have an end-comma</p>

<p>JSON <i>separates</i> array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them:</p>

<pre><code>   [
      1,
      2, &lt;- this comma not normally allowed
   ]
   {
      &quot;k1&quot;: &quot;v1&quot;,
      &quot;k2&quot;: &quot;v2&quot;, &lt;- this comma not normally allowed
   }</code></pre>

</li>
<li><p>shell-style &#39;#&#39;-comments</p>

<p>Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed.</p>

<pre><code>  [
     1, # this comment not allowed in JSON
        # neither this one...
  ]</code></pre>

</li>
<li><p>literal ASCII TAB characters in strings</p>

<p>Literal ASCII TAB characters are now allowed in strings (and treated as <code>\t</code>).</p>

<pre><code>  [
     &quot;Hello\tWorld&quot;,
     &quot;Hello&lt;TAB&gt;World&quot;, # literal &lt;TAB&gt; would not normally be allowed
  ]</code></pre>

</li>
</ul>

</dd>
<dt id="$json-=-$json-&gt;canonical-([$enable])"><a id="json----json--canonical--enable"></a>$json = $json-&gt;canonical ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_canonical"><a id="enabled----json--get_canonical"></a>$enabled = $json-&gt;get_canonical</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will output JSON objects by sorting their keys. This is adding a comparatively high overhead.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script, and can change even within the same run from 5.18 onwards).</p>

<p>This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl.</p>

<p>This setting has no effect when decoding JSON texts.</p>

<p>This setting has currently no effect on tied hashes.</p>

</dd>
<dt id="$json-=-$json-&gt;allow_nonref-([$enable])"><a id="json----json--allow_nonref--enable"></a>$json = $json-&gt;allow_nonref ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_allow_nonref"><a id="enabled----json--get_allow_nonref"></a>$enabled = $json-&gt;get_allow_nonref</dt>
<dd>

<p>Unlike other boolean options, this opotion is enabled by default beginning with version <code>4.0</code>. See <a href="./JSON::XS.html#SECURITY-CONSIDERATIONS">&quot;SECURITY CONSIDERATIONS&quot;</a> for the gory details.</p>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, <code>decode</code> will accept those JSON values instead of croaking.</p>

<p>If <code>$enable</code> is false, then the <code>encode</code> method will croak if it isn&#39;t passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, <code>decode</code> will croak if given something that is not a JSON object or array.</p>

<p>Example, encode a Perl scalar as JSON value without enabled <code>allow_nonref</code>, resulting in an error:</p>

<pre><code>   JSON::XS-&gt;new-&gt;allow_nonref (0)-&gt;encode (&quot;Hello, World!&quot;)
   =&gt; hash- or arrayref expected...</code></pre>

</dd>
<dt id="$json-=-$json-&gt;allow_unknown-([$enable])"><a id="json----json--allow_unknown--enable"></a>$json = $json-&gt;allow_unknown ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_allow_unknown"><a id="enabled----json--get_allow_unknown"></a>$enabled = $json-&gt;get_allow_unknown</dt>
<dd>

<p>If <code>$enable</code> is true (or missing), then <code>encode</code> will <i>not</i> throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON <code>null</code> value. Note that blessed objects are not included here and are handled separately by c&lt;allow_nonref&gt;.</p>

<p>If <code>$enable</code> is false (the default), then <code>encode</code> will throw an exception when it encounters anything it cannot encode as JSON.</p>

<p>This option does not affect <code>decode</code> in any way, and it is recommended to leave it off unless you know your communications partner.</p>

</dd>
<dt id="$json-=-$json-&gt;allow_blessed-([$enable])"><a id="json----json--allow_blessed--enable"></a>$json = $json-&gt;allow_blessed ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_allow_blessed"><a id="enabled----json--get_allow_blessed"></a>$enabled = $json-&gt;get_allow_blessed</dt>
<dd>

<p>See <a href="./JSON::XS.html#OBJECT-SERIALISATION">&quot;OBJECT SERIALISATION&quot;</a> for details.</p>

<p>If <code>$enable</code> is true (or missing), then the <code>encode</code> method will not barf when it encounters a blessed reference that it cannot convert otherwise. Instead, a JSON <code>null</code> value is encoded instead of the object.</p>

<p>If <code>$enable</code> is false (the default), then <code>encode</code> will throw an exception when it encounters a blessed object that it cannot convert otherwise.</p>

<p>This setting has no effect on <code>decode</code>.</p>

</dd>
<dt id="$json-=-$json-&gt;convert_blessed-([$enable])"><a id="json----json--convert_blessed--enable"></a>$json = $json-&gt;convert_blessed ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_convert_blessed"><a id="enabled----json--get_convert_blessed"></a>$enabled = $json-&gt;get_convert_blessed</dt>
<dd>

<p>See <a href="./JSON::XS.html#OBJECT-SERIALISATION">&quot;OBJECT SERIALISATION&quot;</a> for details.</p>

<p>If <code>$enable</code> is true (or missing), then <code>encode</code>, upon encountering a blessed object, will check for the availability of the <code>TO_JSON</code> method on the object&#39;s class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object.</p>

<p>The <code>TO_JSON</code> method may safely call die if it wants. If <code>TO_JSON</code> returns other blessed objects, those will be handled in the same way. <code>TO_JSON</code> must take care of not causing an endless recursion cycle (== crash) in this case. The name of <code>TO_JSON</code> was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with any <code>to_json</code> function or method.</p>

<p>If <code>$enable</code> is false (the default), then <code>encode</code> will not consider this type of conversion.</p>

<p>This setting has no effect on <code>decode</code>.</p>

</dd>
<dt id="$json-=-$json-&gt;allow_tags-([$enable])"><a id="json----json--allow_tags--enable"></a>$json = $json-&gt;allow_tags ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_allow_tags"><a id="enabled----json--get_allow_tags"></a>$enabled = $json-&gt;get_allow_tags</dt>
<dd>

<p>See <a href="./JSON::XS.html#OBJECT-SERIALISATION">&quot;OBJECT SERIALISATION&quot;</a> for details.</p>

<p>If <code>$enable</code> is true (or missing), then <code>encode</code>, upon encountering a blessed object, will check for the availability of the <code>FREEZE</code> method on the object&#39;s class. If found, it will be used to serialise the object into a nonstandard tagged JSON value (that JSON decoders cannot decode).</p>

<p>It also causes <code>decode</code> to parse such tagged JSON values and deserialise them via a call to the <code>THAW</code> method.</p>

<p>If <code>$enable</code> is false (the default), then <code>encode</code> will not consider this type of conversion, and tagged JSON values will cause a parse error in <code>decode</code>, as if tags were not part of the grammar.</p>

</dd>
<dt id="$json-&gt;boolean_values-([$false,-$true])"><a id="json--boolean_values--false---true"></a>$json-&gt;boolean_values ([$false, $true])</dt>
<dd>

</dd>
<dt id="($false,-$true)-=-$json-&gt;get_boolean_values"><a id="false---true-----json--get_boolean_values"></a>($false, $true) = $json-&gt;get_boolean_values</dt>
<dd>

<p>By default, JSON booleans will be decoded as overloaded <code>$Types::Serialiser::false</code> and <code>$Types::Serialiser::true</code> objects.</p>

<p>With this method you can specify your own boolean values for decoding - on decode, JSON <code>false</code> will be decoded as a copy of <code>$false</code>, and JSON <code>true</code> will be decoded as <code>$true</code> (&quot;copy&quot; here is the same thing as assigning a value to another variable, i.e. <code>$copy = $false</code>).</p>

<p>Calling this method without any arguments will reset the booleans to their default values.</p>

<p><code>get_boolean_values</code> will return both <code>$false</code> and <code>$true</code> values, or the empty list when they are set to the default.</p>

</dd>
<dt id="$json-=-$json-&gt;filter_json_object-([$coderef-&gt;($hashref)])"><a id="json----json--filter_json_object--coderef--hashref"></a>$json = $json-&gt;filter_json_object ([$coderef-&gt;($hashref)])</dt>
<dd>

<p>When <code>$coderef</code> is specified, it will be called from <code>decode</code> each time it decodes a JSON object. The only argument is a reference to the newly-created hash. If the code reference returns a single scalar (which need not be a reference), this value (or rather a copy of it) is inserted into the deserialised data structure. If it returns an empty list (NOTE: <i>not</i> <code>undef</code>, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably.</p>

<p>When <code>$coderef</code> is omitted or undefined, any existing callback will be removed and <code>decode</code> will not change the deserialised hash in any way.</p>

<p>Example, convert all JSON objects into the integer 5:</p>

<pre><code>   my $js = JSON::XS-&gt;new-&gt;filter_json_object (sub { 5 });
   # returns [5]
   $js-&gt;decode (&#39;[{}]&#39;)
   # throw an exception because allow_nonref is not enabled
   # so a lone 5 is not allowed.
   $js-&gt;decode (&#39;{&quot;a&quot;:1, &quot;b&quot;:2}&#39;);</code></pre>

</dd>
<dt id="$json-=-$json-&gt;filter_json_single_key_object-($key-[=&gt;-$coderef-&gt;($value)])"><a id="json----json--filter_json_single_key_object--key----coderef--value"></a>$json = $json-&gt;filter_json_single_key_object ($key [=&gt; $coderef-&gt;($value)])</dt>
<dd>

<p>Works remotely similar to <code>filter_json_object</code>, but is only called for JSON objects having a single key named <code>$key</code>.</p>

<p>This <code>$coderef</code> is called before the one specified via <code>filter_json_object</code>, if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even <code>undef</code> but the empty list), the callback from <code>filter_json_object</code> will be called next, as if no single-key callback were specified.</p>

<p>If <code>$coderef</code> is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key.</p>

<p>As this callback gets called less often then the <code>filter_json_object</code> one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialise Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it&#39;s basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash.</p>

<p>Typical names for the single object key are <code>__class_whatever__</code>, or <code>$__dollars_are_rarely_used__$</code> or <code>}ugly_brace_placement</code>, or even things like <code>__class_md5sum(classname)__</code>, to reduce the risk of clashing with real hashes.</p>

<p>Example, decode JSON objects of the form <code>{ &quot;__widget__&quot; =&gt; &lt;id&gt; }</code> into the corresponding <code>$WIDGET{&lt;id&gt;}</code> object:</p>

<pre><code>   # return whatever is in $WIDGET{5}:
   JSON::XS
      -&gt;new
      -&gt;filter_json_single_key_object (__widget__ =&gt; sub {
            $WIDGET{ $_[0] }
         })
      -&gt;decode (&#39;{&quot;__widget__&quot;: 5&#39;)

   # this can be used with a TO_JSON method in some &quot;widget&quot; class
   # for serialisation to json:
   sub WidgetBase::TO_JSON {
      my ($self) = @_;

      unless ($self-&gt;{id}) {
         $self-&gt;{id} = ..get..some..id..;
         $WIDGET{$self-&gt;{id}} = $self;
      }

      { __widget__ =&gt; $self-&gt;{id} }
   }</code></pre>

</dd>
<dt id="$json-=-$json-&gt;shrink-([$enable])"><a id="json----json--shrink--enable"></a>$json = $json-&gt;shrink ([$enable])</dt>
<dd>

</dd>
<dt id="$enabled-=-$json-&gt;get_shrink"><a id="enabled----json--get_shrink"></a>$enabled = $json-&gt;get_shrink</dt>
<dd>

<p>Perl usually over-allocates memory a bit when allocating space for strings. This flag optionally resizes strings generated by either <code>encode</code> or <code>decode</code> to their minimum size possible. This can save memory when your JSON texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less space in general (and some buggy Perl or C code might even rely on that internal representation being used).</p>

<p>The actual definition of what shrink does might change in future versions, but it will always try to save space at the expense of time.</p>

<p>If <code>$enable</code> is true (or missing), the string returned by <code>encode</code> will be shrunk-to-fit, while all strings generated by <code>decode</code> will also be shrunk-to-fit.</p>

<p>If <code>$enable</code> is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster.</p>

<p>In the future, this setting might control other things, such as converting strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space.</p>

</dd>
<dt id="$json-=-$json-&gt;max_depth-([$maximum_nesting_depth])"><a id="json----json--max_depth--maximum_nesting_depth"></a>$json = $json-&gt;max_depth ([$maximum_nesting_depth])</dt>
<dd>

</dd>
<dt id="$max_depth-=-$json-&gt;get_max_depth"><a id="max_depth----json--get_max_depth"></a>$max_depth = $json-&gt;get_max_depth</dt>
<dd>

<p>Sets the maximum nesting level (default <code>512</code>) accepted while encoding or decoding. If a higher nesting level is detected in JSON text or a Perl data structure, then the encoder and decoder will stop and croak at that point.</p>

<p>Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of <code>{</code> or <code>[</code> characters without their matching closing parenthesis crossed to reach a given character in a string.</p>

<p>Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array.</p>

<p>If no argument is given, the highest possible setting will be used, which is rarely useful.</p>

<p>Note that nesting is implemented by recursion in C. The default value has been chosen to be as large as typical operating systems allow without crashing.</p>

<p>See SECURITY CONSIDERATIONS, below, for more info on why this is useful.</p>

</dd>
<dt id="$json-=-$json-&gt;max_size-([$maximum_string_size])"><a id="json----json--max_size--maximum_string_size"></a>$json = $json-&gt;max_size ([$maximum_string_size])</dt>
<dd>

</dd>
<dt id="$max_size-=-$json-&gt;get_max_size"><a id="max_size----json--get_max_size"></a>$max_size = $json-&gt;get_max_size</dt>
<dd>

<p>Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is <code>0</code>, meaning no limit. When <code>decode</code> is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on <code>encode</code> (yet).</p>

<p>If no argument is given, the limit check will be deactivated (same as when <code>0</code> is specified).</p>

<p>See SECURITY CONSIDERATIONS, below, for more info on why this is useful.</p>

</dd>
<dt id="$json_text-=-$json-&gt;encode-($perl_scalar)"><a id="json_text----json--encode--perl_scalar"></a>$json_text = $json-&gt;encode ($perl_scalar)</dt>
<dd>

<p>Converts the given Perl value or data structure to its JSON representation. Croaks on error.</p>

</dd>
<dt id="$perl_scalar-=-$json-&gt;decode-($json_text)"><a id="perl_scalar----json--decode--json_text"></a>$perl_scalar = $json-&gt;decode ($json_text)</dt>
<dd>

<p>The opposite of <code>encode</code>: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error.</p>

</dd>
<dt id="($perl_scalar,-$characters)-=-$json-&gt;decode_prefix-($json_text)"><a id="perl_scalar---characters-----json--decode_prefix--json_text"></a>($perl_scalar, $characters) = $json-&gt;decode_prefix ($json_text)</dt>
<dd>

<p>This works like the <code>decode</code> method, but instead of raising an exception when there is trailing garbage after the first JSON object, it will silently stop parsing there and return the number of characters consumed so far.</p>

<p>This is useful if your JSON texts are not delimited by an outer protocol and you need to know where the JSON text ends.</p>

<pre><code>   JSON::XS-&gt;new-&gt;decode_prefix (&quot;[1] the tail&quot;)
   =&gt; ([1], 3)</code></pre>

</dd>
</dl>

<h1 id="INCREMENTAL-PARSING"><a id="INCREMENTAL"></a>INCREMENTAL PARSING</h1>

<p>In some cases, there is the need for incremental parsing of JSON texts. While this module always has to keep both JSON text and resulting Perl data structure in memory at one time, it does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to using <code>decode_prefix</code> to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls).</p>

<p>JSON::XS will only attempt to parse the JSON text once it is sure it has enough text to get a decisive result, using a very simple but truly incremental parser. This means that it sometimes won&#39;t stop as early as the full parser, for example, it doesn&#39;t detect mismatched parentheses. The only thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. This means you need to set resource limits (e.g. <code>max_size</code>) to ensure the parser will stop parsing in the presence if syntax errors.</p>

<p>The following methods implement this incremental parser.</p>

<dl>

<dt id="[void,-scalar-or-list-context]-=-$json-&gt;incr_parse-([$string])"><a id="void--scalar-or-list-context-----json--incr_parse--string"></a>[void, scalar or list context] = $json-&gt;incr_parse ([$string])</dt>
<dd>

<p>This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional).</p>

<p>If <code>$string</code> is given, then this string is appended to the already existing JSON fragment stored in the <code>$json</code> object.</p>

<p>After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want.</p>

<p>If the method is called in scalar context, then it will try to extract exactly <i>one</i> JSON object. If that is successful, it will return this object, otherwise it will return <code>undef</code>. If there is a parse error, this method will croak just as <code>decode</code> would do (one can then use <code>incr_skip</code> to skip the erroneous part). This is the most common way of using the method.</p>

<p>And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators (other than whitespace) between the JSON objects or arrays, instead they must be concatenated back-to-back. If an error occurs, an exception will be raised as in the scalar context case. Note that in this case, any previously-parsed JSON texts will be lost.</p>

<p>Example: Parse some JSON arrays/objects in a given string and return them.</p>

<pre><code>   my @objs = JSON::XS-&gt;new-&gt;incr_parse (&quot;[5][7][1,2]&quot;);</code></pre>

</dd>
<dt id="$lvalue_string-=-$json-&gt;incr_text"><a id="lvalue_string----json--incr_text"></a>$lvalue_string = $json-&gt;incr_text</dt>
<dd>

<p>This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This <i>only</i> works when a preceding call to <code>incr_parse</code> in <i>scalar context</i> successfully returned an object. Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it <i>will</i> fail under real world conditions). As a special exception, you can also call this method before having parsed anything.</p>

<p>That means you can only use this function to look at or manipulate text before or after complete JSON objects, not while the parser is in the middle of parsing a JSON object.</p>

<p>This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas).</p>

</dd>
<dt id="$json-&gt;incr_skip"><a id="json--incr_skip"></a>$json-&gt;incr_skip</dt>
<dd>

<p>This will reset the state of the incremental parser and will remove the parsed text from the input buffer so far. This is useful after <code>incr_parse</code> died, in which case the input buffer and incremental parser state is left unchanged, to skip the text parsed so far and to reset the parse state.</p>

<p>The difference to <code>incr_reset</code> is that only text until the parse error occurred is removed.</p>

</dd>
<dt id="$json-&gt;incr_reset"><a id="json--incr_reset"></a>$json-&gt;incr_reset</dt>
<dd>

<p>This completely resets the incremental parser, that is, after this call, it will be as if the parser had never parsed anything.</p>

<p>This is useful if you want to repeatedly parse JSON objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode.</p>

</dd>
</dl>

<h2 id="LIMITATIONS">LIMITATIONS</h2>

<p>The incremental parser is a non-exact parser: it works by gathering as much text as possible that <i>could</i> be a valid JSON text, followed by trying to decode it.</p>

<p>That means it sometimes needs to read more data than strictly necessary to diagnose an invalid JSON text. For example, after parsing the following fragment, the parser <i>could</i> stop with an error, as this fragment <i>cannot</i> be the beginning of a valid JSON text:</p>

<pre><code>   [,</code></pre>

<p>In reality, hopwever, the parser might continue to read data until a length limit is exceeded or it finds a closing bracket.</p>

<h2 id="EXAMPLES">EXAMPLES</h2>

<p>Some examples will make all this clearer. First, a simple example that works similarly to <code>decode_prefix</code>: We want to decode the JSON object at the start of a string and identify the portion after the JSON object:</p>

<pre><code>   my $text = &quot;[1,2,3] hello&quot;;

   my $json = new JSON::XS;

   my $obj = $json-&gt;incr_parse ($text)
      or die &quot;expected JSON object or array at beginning of string&quot;;

   my $tail = $json-&gt;incr_text;
   # $tail now contains &quot; hello&quot;</code></pre>

<p>Easy, isn&#39;t it?</p>

<p>Now for a more complicated example: Imagine a hypothetical protocol where you read some requests from a TCP stream, and each request is a JSON array, without any separation between them (in fact, it is often useful to use newlines as &quot;separators&quot;, as these get interpreted as whitespace at the start of the JSON text, which makes it possible to test said protocol with <code>telnet</code>...).</p>

<p>Here is how you&#39;d do it (it is trivial to write this in an event-based manner):</p>

<pre><code>   my $json = new JSON::XS;

   # read some data from the socket
   while (sysread $socket, my $buf, 4096) {

      # split and decode as many requests as possible
      for my $request ($json-&gt;incr_parse ($buf)) {
         # act on the $request
      }
   }</code></pre>

<p>Another complicated example: Assume you have a string with JSON objects or arrays, all separated by (optional) comma characters (e.g. <code>[1],[2], [3]</code>). To parse them, we have to skip the commas between the JSON texts, and here is where the lvalue-ness of <code>incr_text</code> comes in useful:</p>

<pre><code>   my $text = &quot;[1],[2], [3]&quot;;
   my $json = new JSON::XS;

   # void context, so no parsing done
   $json-&gt;incr_parse ($text);

   # now extract as many objects as possible. note the
   # use of scalar context so incr_text can be called.
   while (my $obj = $json-&gt;incr_parse) {
      # do something with $obj

      # now skip the optional comma
      $json-&gt;incr_text =~ s/^ \s* , //x;
   }</code></pre>

<p>Now lets go for a very complex example: Assume that you have a gigantic JSON array-of-objects, many gigabytes in size, and you want to parse it, but you cannot load it into memory fully (this has actually happened in the real world :).</p>

<p>Well, you lost, you have to implement your own JSON parser. But JSON::XS can still help you: You implement a (very simple) array parser and let JSON decode the array elements, which are all full JSON objects on their own (this wouldn&#39;t work if the array elements could be JSON numbers, for example):</p>

<pre><code>   my $json = new JSON::XS;

   # open the monster
   open my $fh, &quot;&lt;bigfile.json&quot;
      or die &quot;bigfile: $!&quot;;

   # first parse the initial &quot;[&quot;
   for (;;) {
      sysread $fh, my $buf, 65536
         or die &quot;read error: $!&quot;;
      $json-&gt;incr_parse ($buf); # void context, so no parsing

      # Exit the loop once we found and removed(!) the initial &quot;[&quot;.
      # In essence, we are (ab-)using the $json object as a simple scalar
      # we append data to.
      last if $json-&gt;incr_text =~ s/^ \s* \[ //x;
   }

   # now we have the skipped the initial &quot;[&quot;, so continue
   # parsing all the elements.
   for (;;) {
      # in this loop we read data until we got a single JSON object
      for (;;) {
         if (my $obj = $json-&gt;incr_parse) {
            # do something with $obj
            last;
         }

         # add more data
         sysread $fh, my $buf, 65536
            or die &quot;read error: $!&quot;;
         $json-&gt;incr_parse ($buf); # void context, so no parsing
      }

      # in this loop we read data until we either found and parsed the
      # separating &quot;,&quot; between elements, or the final &quot;]&quot;
      for (;;) {
         # first skip whitespace
         $json-&gt;incr_text =~ s/^\s*//;

         # if we find &quot;]&quot;, we are done
         if ($json-&gt;incr_text =~ s/^\]//) {
            print &quot;finished.\n&quot;;
            exit;
         }

         # if we find &quot;,&quot;, we can continue with the next element
         if ($json-&gt;incr_text =~ s/^,//) {
            last;
         }

         # if we find anything else, we have a parse error!
         if (length $json-&gt;incr_text) {
            die &quot;parse error near &quot;, $json-&gt;incr_text;
         }

         # else add more data
         sysread $fh, my $buf, 65536
            or die &quot;read error: $!&quot;;
         $json-&gt;incr_parse ($buf); # void context, so no parsing
      }</code></pre>

<p>This is a complex example, but most of the complexity comes from the fact that we are trying to be correct (bear with me if I am wrong, I never ran the above example :).</p>

<h1 id="MAPPING">MAPPING</h1>

<p>This section describes how JSON::XS maps Perl values to JSON values and vice versa. These mappings are designed to &quot;do the right thing&quot; in most circumstances automatically, preserving round-tripping characteristics (what you put in comes out as something equivalent).</p>

<p>For the more enlightened: note that in the following descriptions, lowercase <i>perl</i> refers to the Perl interpreter, while uppercase <i>Perl</i> refers to the abstract Perl language itself.</p>

<h2 id="JSON-&gt;-PERL"><a id="JSON"></a><a id="JSON---PERL"></a>JSON -&gt; PERL</h2>

<dl>

<dt id="object">object</dt>
<dd>

<p>A JSON object becomes a reference to a hash in Perl. No ordering of object keys is preserved (JSON does not preserve object key ordering itself).</p>

</dd>
<dt id="array">array</dt>
<dd>

<p>A JSON array becomes a reference to an array in Perl.</p>

</dd>
<dt id="string">string</dt>
<dd>

<p>A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary.</p>

</dd>
<dt id="number">number</dt>
<dd>

<p>A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers.</p>

<p>If the number consists of digits only, JSON::XS will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded to a JSON string).</p>

<p>Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number).</p>

<p>Note that precision is not accuracy - binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, JSON::XS only guarantees precision up to but not including the least significant bit.</p>

</dd>
<dt id="true,-false"><a id="true"></a><a id="true--false"></a>true, false</dt>
<dd>

<p>These JSON atoms become <code>Types::Serialiser::true</code> and <code>Types::Serialiser::false</code>, respectively. They are overloaded to act almost exactly like the numbers <code>1</code> and <code>0</code>. You can check whether a scalar is a JSON boolean by using the <code>Types::Serialiser::is_bool</code> function (after <code>use Types::Serialier</code>, of course).</p>

</dd>
<dt id="null">null</dt>
<dd>

<p>A JSON null atom becomes <code>undef</code> in Perl.</p>

</dd>
<dt id="shell-style-comments-(#-text)"><a id="shell"></a><a id="shell-style-comments---text"></a>shell-style comments (<code># <i>text</i></code>)</dt>
<dd>

<p>As a nonstandard extension to the JSON syntax that is enabled by the <code>relaxed</code> setting, shell-style comments are allowed. They can start anywhere outside strings and go till the end of the line.</p>

</dd>
<dt id="tagged-values-((tag)value)."><a id="tagged"></a><a id="tagged-values--tag-value"></a>tagged values (<code>(<i>tag</i>)<i>value</i></code>).</dt>
<dd>

<p>Another nonstandard extension to the JSON syntax, enabled with the <code>allow_tags</code> setting, are tagged values. In this implementation, the <i>tag</i> must be a perl package/class name encoded as a JSON string, and the <i>value</i> must be a JSON array encoding optional constructor arguments.</p>

<p>See <a href="./JSON::XS.html#OBJECT-SERIALISATION">&quot;OBJECT SERIALISATION&quot;</a>, below, for details.</p>

</dd>
</dl>

<h2 id="PERL-&gt;-JSON"><a id="PERL"></a><a id="PERL---JSON"></a>PERL -&gt; JSON</h2>

<p>The mapping from Perl to JSON is slightly more difficult, as Perl is a truly typeless language, so we can only guess which JSON type is meant by a Perl value.</p>

<dl>

<dt id="hash-references"><a id="hash"></a>hash references</dt>
<dd>

<p>Perl hash references become JSON objects. As there is no inherent ordering in hash keys (or JSON objects), they will usually be encoded in a pseudo-random order. JSON::XS can optionally sort the hash keys (determined by the <i>canonical</i> flag), so the same datastructure will serialise to the same JSON text (given same settings and version of JSON::XS), but this incurs a runtime overhead and is only rarely useful, e.g. when you want to compare some JSON text against another for equality.</p>

</dd>
<dt id="array-references"><a id="array1"></a>array references</dt>
<dd>

<p>Perl array references become JSON arrays.</p>

</dd>
<dt id="other-references"><a id="other"></a>other references</dt>
<dd>

<p>Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers <code>0</code> and <code>1</code>, which get turned into <code>false</code> and <code>true</code> atoms in JSON.</p>

<p>Since <code>JSON::XS</code> uses the boolean model from <a href="https://metacpan.org/pod/Types::Serialiser">Types::Serialiser</a>, you can also <code>use Types::Serialiser</code> and then use <code>Types::Serialiser::false</code> and <code>Types::Serialiser::true</code> to improve readability.</p>

<pre><code>   use Types::Serialiser;
   encode_json [\0, Types::Serialiser::true]      # yields [false,true]</code></pre>

</dd>
<dt id="Types::Serialiser::true,-Types::Serialiser::false"><a id="Types"></a><a id="Types::Serialiser::true--Types::Serialiser::false"></a>Types::Serialiser::true, Types::Serialiser::false</dt>
<dd>

<p>These special values from the <a href="https://metacpan.org/pod/Types::Serialiser">Types::Serialiser</a> module become JSON true and JSON false values, respectively. You can also use <code>\1</code> and <code>\0</code> directly if you want.</p>

</dd>
<dt id="blessed-objects"><a id="blessed"></a>blessed objects</dt>
<dd>

<p>Blessed objects are not directly representable in JSON, but <code>JSON::XS</code> allows various ways of handling objects. See <a href="./JSON::XS.html#OBJECT-SERIALISATION">&quot;OBJECT SERIALISATION&quot;</a>, below, for details.</p>

</dd>
<dt id="simple-scalars"><a id="simple"></a>simple scalars</dt>
<dd>

<p>Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: JSON::XS will encode undefined scalars as JSON <code>null</code> values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value:</p>

<pre><code>   # dump as number
   encode_json [2]                      # yields [2]
   encode_json [-3.0e17]                # yields [-3e+17]
   my $value = 5; encode_json [$value]  # yields [5]

   # used as string, so dump as string
   print $value;
   encode_json [$value]                 # yields [&quot;5&quot;]

   # undef becomes null
   encode_json [undef]                  # yields [null]</code></pre>

<p>You can force the type to be a JSON string by stringifying it:</p>

<pre><code>   my $x = 3.1; # some variable containing a number
   &quot;$x&quot;;        # stringified
   $x .= &quot;&quot;;    # another, more awkward way to stringify
   print $x;    # perl does it for you, too, quite often</code></pre>

<p>You can force the type to be a JSON number by numifying it:</p>

<pre><code>   my $x = &quot;3&quot;; # some variable containing a string
   $x += 0;     # numify it, ensuring it will be dumped as a number
   $x *= 1;     # same thing, the choice is yours.</code></pre>

<p>You can not currently force the type in other, less obscure, ways. Tell me if you need this capability (but don&#39;t forget to explain why it&#39;s needed :).</p>

<p>Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN&#39;s - these cannot be represented in JSON, and it is an error to pass those in.</p>

</dd>
</dl>

<h2 id="OBJECT-SERIALISATION"><a id="OBJECT1"></a>OBJECT SERIALISATION</h2>

<p>As JSON cannot directly represent Perl objects, you have to choose between a pure JSON representation (without the ability to deserialise the object automatically again), and a nonstandard extension to the JSON syntax, tagged values.</p>

<h3 id="SERIALISATION">SERIALISATION</h3>

<p>What happens when <code>JSON::XS</code> encounters a Perl object depends on the <code>allow_blessed</code>, <code>convert_blessed</code> and <code>allow_tags</code> settings, which are used in this order:</p>

<dl>

<dt id="1.-allow_tags-is-enabled-and-the-object-has-a-FREEZE-method."><a id="11"></a><a id="allow_tags-is-enabled-and-the-object-has-a-FREEZE-method"></a>1. <code>allow_tags</code> is enabled and the object has a <code>FREEZE</code> method.</dt>
<dd>

<p>In this case, <code>JSON::XS</code> uses the <a href="https://metacpan.org/pod/Types::Serialiser">Types::Serialiser</a> object serialisation protocol to create a tagged JSON value, using a nonstandard extension to the JSON syntax.</p>

<p>This works by invoking the <code>FREEZE</code> method on the object, with the first argument being the object to serialise, and the second argument being the constant string <code>JSON</code> to distinguish it from other serialisers.</p>

<p>The <code>FREEZE</code> method can return any number of values (i.e. zero or more). These values and the paclkage/classname of the object will then be encoded as a tagged JSON value in the following format:</p>

<pre><code>   (&quot;classname&quot;)[FREEZE return values...]</code></pre>

<p>e.g.:</p>

<pre><code>   (&quot;URI&quot;)[&quot;http://www.google.com/&quot;]
   (&quot;MyDate&quot;)[2013,10,29]
   (&quot;ImageData::JPEG&quot;)[&quot;Z3...VlCg==&quot;]</code></pre>

<p>For example, the hypothetical <code>My::Object</code> <code>FREEZE</code> method might use the objects <code>type</code> and <code>id</code> members to encode the object:</p>

<pre><code>   sub My::Object::FREEZE {
      my ($self, $serialiser) = @_;

      ($self-&gt;{type}, $self-&gt;{id})
   }</code></pre>

</dd>
<dt id="2.-convert_blessed-is-enabled-and-the-object-has-a-TO_JSON-method."><a id="21"></a><a id="convert_blessed-is-enabled-and-the-object-has-a-TO_JSON-method"></a>2. <code>convert_blessed</code> is enabled and the object has a <code>TO_JSON</code> method.</dt>
<dd>

<p>In this case, the <code>TO_JSON</code> method of the object is invoked in scalar context. It must return a single scalar that can be directly encoded into JSON. This scalar replaces the object in the JSON text.</p>

<p>For example, the following <code>TO_JSON</code> method will convert all <a href="URI.html">URI</a> objects to JSON strings when serialised. The fatc that these values originally were <a href="URI.html">URI</a> objects is lost.</p>

<pre><code>   sub URI::TO_JSON {
      my ($uri) = @_;
      $uri-&gt;as_string
   }</code></pre>

</dd>
<dt id="3.-allow_blessed-is-enabled."><a id="31"></a><a id="allow_blessed-is-enabled"></a>3. <code>allow_blessed</code> is enabled.</dt>
<dd>

<p>The object will be serialised as a JSON null value.</p>

</dd>
<dt id="4.-none-of-the-above"><a id="41"></a><a id="none-of-the-above"></a>4. none of the above</dt>
<dd>

<p>If none of the settings are enabled or the respective methods are missing, <code>JSON::XS</code> throws an exception.</p>

</dd>
</dl>

<h3 id="DESERIALISATION">DESERIALISATION</h3>

<p>For deserialisation there are only two cases to consider: either nonstandard tagging was used, in which case <code>allow_tags</code> decides, or objects cannot be automatically be deserialised, in which case you can use postprocessing or the <code>filter_json_object</code> or <code>filter_json_single_key_object</code> callbacks to get some real objects our of your JSON.</p>

<p>This section only considers the tagged value case: I a tagged JSON object is encountered during decoding and <code>allow_tags</code> is disabled, a parse error will result (as if tagged values were not part of the grammar).</p>

<p>If <code>allow_tags</code> is enabled, <code>JSON::XS</code> will look up the <code>THAW</code> method of the package/classname used during serialisation (it will not attempt to load the package as a Perl module). If there is no such method, the decoding will fail with an error.</p>

<p>Otherwise, the <code>THAW</code> method is invoked with the classname as first argument, the constant string <code>JSON</code> as second argument, and all the values from the JSON array (the values originally returned by the <code>FREEZE</code> method) as remaining arguments.</p>

<p>The method must then return the object. While technically you can return any Perl scalar, you might have to enable the <code>enable_nonref</code> setting to make that work in all cases, so better return an actual blessed reference.</p>

<p>As an example, let&#39;s implement a <code>THAW</code> function that regenerates the <code>My::Object</code> from the <code>FREEZE</code> example earlier:</p>

<pre><code>   sub My::Object::THAW {
      my ($class, $serialiser, $type, $id) = @_;

      $class-&gt;new (type =&gt; $type, id =&gt; $id)
   }</code></pre>

<h1 id="ENCODING/CODESET-FLAG-NOTES"><a id="ENCODING"></a><a id="ENCODING-CODESET-FLAG-NOTES"></a>ENCODING/CODESET FLAG NOTES</h1>

<p>The interested reader might have seen a number of flags that signify encodings or codesets - <code>utf8</code>, <code>latin1</code> and <code>ascii</code>. There seems to be some confusion on what these do, so here is a short comparison:</p>

<p><code>utf8</code> controls whether the JSON text created by <code>encode</code> (and expected by <code>decode</code>) is UTF-8 encoded or not, while <code>latin1</code> and <code>ascii</code> only control whether <code>encode</code> escapes character values outside their respective codeset range. Neither of these flags conflict with each other, although some combinations make less sense than others.</p>

<p>Care has been taken to make all flags symmetrical with respect to <code>encode</code> and <code>decode</code>, that is, texts encoded with any combination of these flag values will be correctly decoded when the same flags are used - in general, if you use different flag settings while encoding vs. when decoding you likely have a bug somewhere.</p>

<p>Below comes a verbose discussion of these flags. Note that a &quot;codeset&quot; is simply an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and <i>encodes</i> them, in our case into octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets <i>and</i> encodings at the same time, which can be confusing.</p>

<dl>

<dt id="utf8-flag-disabled"><a id="utf8"></a><code>utf8</code> flag disabled</dt>
<dd>

<p>When <code>utf8</code> is disabled (the default), then <code>encode</code>/<code>decode</code> generate and expect Unicode strings, that is, characters with high ordinal Unicode values (&gt; 255) will be encoded as such characters, and likewise such characters are decoded as-is, no changes to them will be done, except &quot;(re-)interpreting&quot; them as Unicode codepoints or Unicode characters, respectively (to Perl, these are the same thing in strings unless you do funny/weird/dumb stuff).</p>

<p>This is useful when you want to do the encoding yourself (e.g. when you want to have UTF-16 encoded JSON texts) or when some other layer does the encoding for you (for example, when printing to a terminal using a filehandle that transparently encodes to UTF-8 you certainly do NOT want to UTF-8 encode your data first and have Perl encode it another time).</p>

</dd>
<dt id="utf8-flag-enabled"><a id="utf81"></a><code>utf8</code> flag enabled</dt>
<dd>

<p>If the <code>utf8</code>-flag is enabled, <code>encode</code>/<code>decode</code> will encode all characters using the corresponding UTF-8 multi-byte sequence, and will expect your input strings to be encoded as UTF-8, that is, no &quot;character&quot; of the input string must have any value &gt; 255, as UTF-8 does not allow that.</p>

<p>The <code>utf8</code> flag therefore switches between two modes: disabled means you will get a Unicode string in Perl, enabled means you get a UTF-8 encoded octet/binary string in Perl.</p>

</dd>
<dt id="latin1-or-ascii-flags-enabled"><a id="latin1"></a><code>latin1</code> or <code>ascii</code> flags enabled</dt>
<dd>

<p>With <code>latin1</code> (or <code>ascii</code>) enabled, <code>encode</code> will escape characters with ordinal values &gt; 255 (&gt; 127 with <code>ascii</code>) and encode the remaining characters as specified by the <code>utf8</code> flag.</p>

<p>If <code>utf8</code> is disabled, then the result is also correctly encoded in those character sets (as both are proper subsets of Unicode, meaning that a Unicode string with all character values &lt; 256 is the same thing as a ISO-8859-1 string, and a Unicode string with all character values &lt; 128 is the same thing as an ASCII string in Perl).</p>

<p>If <code>utf8</code> is enabled, you still get a correct UTF-8-encoded string, regardless of these flags, just some more characters will be escaped using <code>\uXXXX</code> then before.</p>

<p>Note that ISO-8859-1-<i>encoded</i> strings are not compatible with UTF-8 encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 <i>codeset</i> being a subset of Unicode), while ASCII is.</p>

<p>Surprisingly, <code>decode</code> will ignore these flags and so treat all input values as governed by the <code>utf8</code> flag. If it is disabled, this allows you to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings.</p>

<p>So neither <code>latin1</code> nor <code>ascii</code> are incompatible with the <code>utf8</code> flag - they only govern when the JSON output engine escapes a character or not.</p>

<p>The main use for <code>latin1</code> is to relatively efficiently store binary data as JSON, at the expense of breaking compatibility with most JSON decoders.</p>

<p>The main use for <code>ascii</code> is to force the output to not contain characters with values &gt; 127, which means you can interpret the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and 8-bit-encoding, and still get the same data structure back. This is useful when your channel for JSON transfer is not 8-bit clean or the encoding might be mangled in between (e.g. in mail), and works because ASCII is a proper subset of most 8-bit and multibyte encodings in use in the world.</p>

</dd>
</dl>

<h2 id="JSON-and-ECMAscript"><a id="JSON1"></a>JSON and ECMAscript</h2>

<p>JSON syntax is based on how literals are represented in javascript (the not-standardised predecessor of ECMAscript) which is presumably why it is called &quot;JavaScript Object Notation&quot;.</p>

<p>However, JSON is not a subset (and also not a superset of course) of ECMAscript (the standard) or javascript (whatever browsers actually implement).</p>

<p>If you want to use javascript&#39;s <code>eval</code> function to &quot;parse&quot; JSON, you might run into parse errors for valid JSON texts, or the resulting data structure might not be queryable:</p>

<p>One of the problems is that U+2028 and U+2029 are valid characters inside JSON strings, but are not allowed in ECMAscript string literals, so the following Perl fragment will not output something that can be guaranteed to be parsable by javascript&#39;s <code>eval</code>:</p>

<pre><code>   use JSON::XS;

   print encode_json [chr 0x2028];</code></pre>

<p>The right fix for this is to use a proper JSON parser in your javascript programs, and not rely on <code>eval</code> (see for example Douglas Crockford&#39;s <i>json2.js</i> parser).</p>

<p>If this is not an option, you can, as a stop-gap measure, simply encode to ASCII-only JSON:</p>

<pre><code>   use JSON::XS;

   print JSON::XS-&gt;new-&gt;ascii-&gt;encode ([chr 0x2028]);</code></pre>

<p>Note that this will enlarge the resulting JSON text quite a bit if you have many non-ASCII characters. You might be tempted to run some regexes to only escape U+2028 and U+2029, e.g.:</p>

<pre><code>   # DO NOT USE THIS!
   my $json = JSON::XS-&gt;new-&gt;utf8-&gt;encode ([chr 0x2028]);
   $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028
   $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029
   print $json;</code></pre>

<p>Note that <i>this is a bad idea</i>: the above only works for U+2028 and U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing javascript implementations, however, have issues with other characters as well - using <code>eval</code> naively simply <i>will</i> cause problems.</p>

<p>Another problem is that some javascript implementations reserve some property names for their own purposes (which probably makes them non-ECMAscript-compliant). For example, Iceweasel reserves the <code>__proto__</code> property name for its own purposes.</p>

<p>If that is a problem, you could parse try to filter the resulting JSON output for these property strings, e.g.:</p>

<pre><code>   $json =~ s/&quot;__proto__&quot;\s*:/&quot;__proto__renamed&quot;:/g;</code></pre>

<p>This works because <code>__proto__</code> is not valid outside of strings, so every occurrence of <code>&quot;__proto__&quot;\s*:</code> must be a string used as property name.</p>

<p>If you know of other incompatibilities, please let me know.</p>

<h2 id="JSON-and-YAML"><a id="JSON2"></a>JSON and YAML</h2>

<p>You often hear that JSON is a subset of YAML. This is, however, a mass hysteria(*) and very far from the truth (as of the time of this writing), so let me state it clearly: <i>in general, there is no way to configure JSON::XS to output a data structure as valid YAML</i> that works in all cases.</p>

<p>If you really must use JSON::XS to generate YAML, you should use this algorithm (subject to change in future versions):</p>

<pre><code>   my $to_yaml = JSON::XS-&gt;new-&gt;utf8-&gt;space_after (1);
   my $yaml = $to_yaml-&gt;encode ($ref) . &quot;\n&quot;;</code></pre>

<p>This will <i>usually</i> generate JSON texts that also parse as valid YAML. Please note that YAML has hardcoded limits on (simple) object key lengths that JSON doesn&#39;t have and also has different and incompatible unicode character escape syntax, so you should make sure that your hash keys are noticeably shorter than the 1024 &quot;stream characters&quot; YAML allows and that you do not have characters with codepoint values outside the Unicode BMP (basic multilingual page). YAML also does not allow <code>\/</code> sequences in strings (which JSON::XS does not <i>currently</i> generate, but other JSON generators might).</p>

<p>There might be other incompatibilities that I am not aware of (or the YAML specification has been changed yet again - it does so quite often). In general you should not try to generate YAML with a JSON generator or vice versa, or try to parse JSON with a YAML parser or vice versa: chances are high that you will run into severe interoperability problems when you least expect it.</p>

<dl>

<dt id="(*)"><a id="pod"></a>(*)</dt>
<dd>

<p>I have been pressured multiple times by Brian Ingerson (one of the authors of the YAML specification) to remove this paragraph, despite him acknowledging that the actual incompatibilities exist. As I was personally bitten by this &quot;JSON is YAML&quot; lie, I refused and said I will continue to educate people about these issues, so others do not run into the same problem again and again. After this, Brian called me a (quote)<i>complete and worthless idiot</i>(unquote).</p>

<p>In my opinion, instead of pressuring and insulting people who actually clarify issues with YAML and the wrong statements of some of its proponents, I would kindly suggest reading the JSON spec (which is not that difficult or long) and finally make YAML compatible to it, and educating users about the changes, instead of spreading lies about the real compatibility for many <i>years</i> and trying to silence people who point out that it isn&#39;t true.</p>

<p>Addendum/2009: the YAML 1.2 spec is still incompatible with JSON, even though the incompatibilities have been documented (and are known to Brian) for many years and the spec makes explicit claims that YAML is a superset of JSON. It would be so easy to fix, but apparently, bullying people and corrupting userdata is so much easier.</p>

</dd>
</dl>

<h2 id="SPEED">SPEED</h2>

<p>It seems that JSON::XS is surprisingly fast, as shown in the following tables. They have been generated with the help of the <code>eg/bench</code> program in the JSON::XS distribution, to make it easy to compare on your own system.</p>

<p>First comes a comparison between various modules using a very short single-line JSON string (also available at <a href="http://dist.schmorp.de/misc/json/short.json">http://dist.schmorp.de/misc/json/short.json</a>).</p>

<pre><code>   {&quot;method&quot;: &quot;handleMessage&quot;, &quot;params&quot;: [&quot;user1&quot;,
   &quot;we were just talking&quot;], &quot;id&quot;: null, &quot;array&quot;:[1,11,234,-5,1e5,1e7,
   1,  0]}</code></pre>

<p>It shows the number of encodes/decodes per second (JSON::XS uses the functional interface, while JSON::XS/2 uses the OO interface with pretty-printing and hashkey sorting enabled, JSON::XS/3 enables shrink. JSON::DWIW/DS uses the deserialise function, while JSON::DWIW::FJ uses the from_json method). Higher is better:</p>

<pre><code>   module        |     encode |     decode |
   --------------|------------|------------|
   JSON::DWIW/DS |  86302.551 | 102300.098 |
   JSON::DWIW/FJ |  86302.551 |  75983.768 |
   JSON::PP      |  15827.562 |   6638.658 |
   JSON::Syck    |  63358.066 |  47662.545 |
   JSON::XS      | 511500.488 | 511500.488 |
   JSON::XS/2    | 291271.111 | 388361.481 |
   JSON::XS/3    | 361577.931 | 361577.931 |
   Storable      |  66788.280 | 265462.278 |
   --------------+------------+------------+</code></pre>

<p>That is, JSON::XS is almost six times faster than JSON::DWIW on encoding, about five times faster on decoding, and over thirty to seventy times faster than JSON&#39;s pure perl implementation. It also compares favourably to Storable for small amounts of data.</p>

<p>Using a longer test string (roughly 18KB, generated from Yahoo! Locals search API (<a href="http://dist.schmorp.de/misc/json/long.json">http://dist.schmorp.de/misc/json/long.json</a>).</p>

<pre><code>   module        |     encode |     decode |
   --------------|------------|------------|
   JSON::DWIW/DS |   1647.927 |   2673.916 |
   JSON::DWIW/FJ |   1630.249 |   2596.128 |
   JSON::PP      |    400.640 |     62.311 |
   JSON::Syck    |   1481.040 |   1524.869 |
   JSON::XS      |  20661.596 |   9541.183 |
   JSON::XS/2    |  10683.403 |   9416.938 |
   JSON::XS/3    |  20661.596 |   9400.054 |
   Storable      |  19765.806 |  10000.725 |
   --------------+------------+------------+</code></pre>

<p>Again, JSON::XS leads by far (except for Storable which non-surprisingly decodes a bit faster).</p>

<p>On large strings containing lots of high Unicode characters, some modules (such as JSON::PC) seem to decode faster than JSON::XS, but the result will be broken due to missing (or wrong) Unicode handling. Others refuse to decode or encode properly, so it was impossible to prepare a fair comparison table for that case.</p>

<h1 id="SECURITY-CONSIDERATIONS"><a id="SECURITY"></a>SECURITY CONSIDERATIONS</h1>

<p>When you are using JSON in a protocol, talking to untrusted potentially hostile creatures requires relatively few measures.</p>

<p>First of all, your JSON decoder should be secure, that is, should not have any buffer overflows. Obviously, this module should ensure that and I am trying hard on making that true, but you never know.</p>

<p>Second, you need to avoid resource-starving attacks. That means you should limit the size of JSON texts you accept, or make sure then when your resources run out, that&#39;s just fine (e.g. by using a separate process that can crash safely). The size of a JSON text in octets or characters is usually a good indication of the size of the resources required to decode it into a Perl structure. While JSON::XS can check the size of the JSON text, it might be too late when you already have it in memory, so you might want to check the size before you accept the string.</p>

<p>Third, JSON::XS recurses using the C stack when decoding objects and arrays. The C stack is a limited resource: for instance, on my amd64 machine with 8MB of stack size I can decode around 180k nested arrays but only 14k nested JSON objects (due to perl itself recursing deeply on croak to free the temporary). If that is exceeded, the program crashes. To be conservative, the default nesting limit is set to 512. If your process has a smaller stack, you should adjust this setting accordingly with the <code>max_depth</code> method.</p>

<p>Something else could bomb you, too, that I forgot to think of. In that case, you get to keep the pieces. I am always open for hints, though...</p>

<p>Also keep in mind that JSON::XS might leak contents of your Perl data structures in its error messages, so when you serialise sensitive information you might want to make sure that exceptions thrown by JSON::XS will not end up in front of untrusted eyes.</p>

<p>If you are using JSON::XS to return packets to consumption by JavaScript scripts in a browser you should have a look at <a href="http://blog.archive.jpsykes.com/47/practical-csrf-and-json-security/">http://blog.archive.jpsykes.com/47/practical-csrf-and-json-security/</a> to see whether you are vulnerable to some common attack vectors (which really are browser design bugs, but it is still you who will have to deal with it, as major browser developers care only for features, not about getting security right).</p>

<h2 id="&quot;OLD&quot;-VS.-&quot;NEW&quot;-JSON-(RFC4627-VS.-RFC7159)"><a id="OLD--VS.--NEW--JSON--RFC4627-VS.-RFC7159"></a>&quot;OLD&quot; VS. &quot;NEW&quot; JSON (RFC4627 VS. RFC7159)</h2>

<p>JSON originally required JSON texts to represent an array or object - scalar values were explicitly not allowed. This has changed, and versions of JSON::XS beginning with <code>4.0</code> reflect this by allowing scalar values by default.</p>

<p>One reason why one might not want this is that this removes a fundamental property of JSON texts, namely that they are self-delimited and self-contained, or in other words, you could take any number of &quot;old&quot; JSON texts and paste them together, and the result would be unambiguously parseable:</p>

<pre><code>   [1,3]{&quot;k&quot;:5}[][null] # four JSON texts, without doubt</code></pre>

<p>By allowing scalars, this property is lost: in the following example, is this one JSON text (the number 12) or two JSON texts (the numbers 1 and 2):</p>

<pre><code>   12    # could be 12, or 1 and 2</code></pre>

<p>Another lost property of &quot;old&quot; JSON is that no lookahead is required to know the end of a JSON text, i.e. the JSON text definitely ended at the last <code>]</code> or <code>}</code> character, there was no need to read extra characters.</p>

<p>For example, a viable network protocol with &quot;old&quot; JSON was to simply exchange JSON texts without delimiter. For &quot;new&quot; JSON, you have to use a suitable delimiter (such as a newline) after every JSON text or ensure you never encode/decode scalar values.</p>

<p>Most protocols do work by only transferring arrays or objects, and the easiest way to avoid problems with the &quot;new&quot; JSON definition is to explicitly disallow scalar values in your encoder and decoder:</p>

<pre><code>   $json_coder = JSON::XS-&gt;new-&gt;allow_nonref (0)</code></pre>

<p>This is a somewhat unhappy situation, and the blame can fully be put on JSON&#39;s inmventor, Douglas Crockford, who unilaterally changed the format in 2006 without consulting the IETF, forcing the IETF to either fork the format or go with it (as I was told, the IETF wasn&#39;t amused).</p>

<h1 id="RELATIONSHIP-WITH-I-JSON"><a id="RELATIONSHIP"></a>RELATIONSHIP WITH I-JSON</h1>

<p>JSON is a somewhat sloppily-defined format - it carries around obvious Javascript baggage, such as not really defining number range, probably because Javascript only has one type of numbers: IEEE 64 bit floats (&quot;binary64&quot;).</p>

<p>For this reaosn, RFC7493 defines &quot;Internet JSON&quot;, which is a restricted subset of JSON that is supposedly more interoperable on the internet.</p>

<p>While <code>JSON::XS</code> does not offer specific support for I-JSON, it of course accepts valid I-JSON and by default implements some of the limitations of I-JSON, such as parsing numbers as perl numbers, which are usually a superset of binary64 numbers.</p>

<p>To generate I-JSON, follow these rules:</p>

<ul>

<li><p>always generate UTF-8</p>

<p>I-JSON must be encoded in UTF-8, the default for <code>encode_json</code>.</p>

</li>
<li><p>numbers should be within IEEE 754 binary64 range</p>

<p>Basically all existing perl installations use binary64 to represent floating point numbers, so all you need to do is to avoid large integers.</p>

</li>
<li><p>objects must not have duplicate keys</p>

<p>This is trivially done, as <code>JSON::XS</code> does not allow duplicate keys.</p>

</li>
<li><p>do not generate scalar JSON texts, use <code>-&gt;allow_nonref (0)</code></p>

<p>I-JSON strongly requests you to only encode arrays and objects into JSON.</p>

</li>
<li><p>times should be strings in ISO 8601 format</p>

<p>There are a myriad of modules on CPAN dealing with ISO 8601 - search for <code>ISO8601</code> on CPAN and use one.</p>

</li>
<li><p>encode binary data as base64</p>

<p>While it&#39;s tempting to just dump binary data as a string (and let <code>JSON::XS</code> do the escaping), for I-JSON, it&#39;s <i>recommended</i> to encode binary data as base64.</p>

</li>
</ul>

<p>There are some other considerations - read RFC7493 for the details if interested.</p>

<h1 id="INTEROPERABILITY-WITH-OTHER-MODULES"><a id="INTEROPERABILITY"></a>INTEROPERABILITY WITH OTHER MODULES</h1>

<p><code>JSON::XS</code> uses the <a href="https://metacpan.org/pod/Types::Serialiser">Types::Serialiser</a> module to provide boolean constants. That means that the JSON true and false values will be comaptible to true and false values of other modules that do the same, such as <a href="https://metacpan.org/pod/JSON::PP">JSON::PP</a> and <a href="https://metacpan.org/pod/CBOR::XS">CBOR::XS</a>.</p>

<h1 id="INTEROPERABILITY-WITH-OTHER-JSON-DECODERS"><a id="INTEROPERABILITY1"></a>INTEROPERABILITY WITH OTHER JSON DECODERS</h1>

<p>As long as you only serialise data that can be directly expressed in JSON, <code>JSON::XS</code> is incapable of generating invalid JSON output (modulo bugs, but <code>JSON::XS</code> has found more bugs in the official JSON testsuite (1) than the official JSON testsuite has found in <code>JSON::XS</code> (0)).</p>

<p>When you have trouble decoding JSON generated by this module using other decoders, then it is very likely that you have an encoding mismatch or the other decoder is broken.</p>

<p>When decoding, <code>JSON::XS</code> is strict by default and will likely catch all errors. There are currently two settings that change this: <code>relaxed</code> makes <code>JSON::XS</code> accept (but not generate) some non-standard extensions, and <code>allow_tags</code> will allow you to encode and decode Perl objects, at the cost of not outputting valid JSON anymore.</p>

<h2 id="TAGGED-VALUE-SYNTAX-AND-STANDARD-JSON-EN/DECODERS"><a id="TAGGED"></a><a id="TAGGED-VALUE-SYNTAX-AND-STANDARD-JSON-EN-DECODERS"></a>TAGGED VALUE SYNTAX AND STANDARD JSON EN/DECODERS</h2>

<p>When you use <code>allow_tags</code> to use the extended (and also nonstandard and invalid) JSON syntax for serialised objects, and you still want to decode the generated When you want to serialise objects, you can run a regex to replace the tagged syntax by standard JSON arrays (it only works for &quot;normal&quot; package names without comma, newlines or single colons). First, the readable Perl version:</p>

<pre><code>   # if your FREEZE methods return no values, you need this replace first:
   $json =~ s/\( \s* (&quot; (?: [^\\&quot;:,]+|\\.|::)* &quot;) \s* \) \s* \[\s*\]/[$1]/gx;

   # this works for non-empty constructor arg lists:
   $json =~ s/\( \s* (&quot; (?: [^\\&quot;:,]+|\\.|::)* &quot;) \s* \) \s* \[/[$1,/gx;</code></pre>

<p>And here is a less readable version that is easy to adapt to other languages:</p>

<pre><code>   $json =~ s/\(\s*(&quot;([^\\&quot;:,]+|\\.|::)*&quot;)\s*\)\s*\[/[$1,/g;</code></pre>

<p>Here is an ECMAScript version (same regex):</p>

<pre><code>   json = json.replace (/\(\s*(&quot;([^\\&quot;:,]+|\\.|::)*&quot;)\s*\)\s*\[/g, &quot;[$1,&quot;);</code></pre>

<p>Since this syntax converts to standard JSON arrays, it might be hard to distinguish serialised objects from normal arrays. You can prepend a &quot;magic number&quot; as first array element to reduce chances of a collision:</p>

<pre><code>   $json =~ s/\(\s*(&quot;([^\\&quot;:,]+|\\.|::)*&quot;)\s*\)\s*\[/[&quot;XU1peReLzT4ggEllLanBYq4G9VzliwKF&quot;,$1,/g;</code></pre>

<p>And after decoding the JSON text, you could walk the data structure looking for arrays with a first element of <code>XU1peReLzT4ggEllLanBYq4G9VzliwKF</code>.</p>

<p>The same approach can be used to create the tagged format with another encoder. First, you create an array with the magic string as first member, the classname as second, and constructor arguments last, encode it as part of your JSON structure, and then:</p>

<pre><code>   $json =~ s/\[\s*&quot;XU1peReLzT4ggEllLanBYq4G9VzliwKF&quot;\s*,\s*(&quot;([^\\&quot;:,]+|\\.|::)*&quot;)\s*,/($1)[/g;</code></pre>

<p>Again, this has some limitations - the magic string must not be encoded with character escapes, and the constructor arguments must be non-empty.</p>

<h1 id="(I-)THREADS"><a id="I--THREADS"></a>(I-)THREADS</h1>

<p>This module is <i>not</i> guaranteed to be ithread (or MULTIPLICITY-) safe and there are no plans to change this. Note that perl&#39;s builtin so-called threads/ithreads are officially deprecated and should not be used.</p>

<h1 id="THE-PERILS-OF-SETLOCALE"><a id="THE"></a>THE PERILS OF SETLOCALE</h1>

<p>Sometimes people avoid the Perl locale support and directly call the system&#39;s setlocale function with <code>LC_ALL</code>.</p>

<p>This breaks both perl and modules such as JSON::XS, as stringification of numbers no longer works correctly (e.g. <code>$x = 0.1; print &quot;$x&quot;+1</code> might print <code>1</code>, and JSON::XS might output illegal JSON as JSON::XS relies on perl to stringify numbers).</p>

<p>The solution is simple: don&#39;t call <code>setlocale</code>, or use it for only those categories you need, such as <code>LC_MESSAGES</code> or <code>LC_CTYPE</code>.</p>

<p>If you need <code>LC_NUMERIC</code>, you should enable it only around the code that actually needs it (avoiding stringification of numbers), and restore it afterwards.</p>

<h1 id="SOME-HISTORY"><a id="SOME"></a>SOME HISTORY</h1>

<p>At the time this module was created there already were a number of JSON modules available on CPAN, so what was the reason to write yet another JSON module? While it seems there are many JSON modules, none of them correctly handled all corner cases, and in most cases their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons.</p>

<p>Beginning with version 2.0 of the JSON module, when both JSON and JSON::XS are installed, then JSON will fall back on JSON::XS (this can be overridden) with no overhead due to emulation (by inheriting constructor and methods). If JSON::XS is not available, it will fall back to the compatible JSON::PP module as backend, so using JSON instead of JSON::XS gives you a portable JSON API that can be fast when you need it and doesn&#39;t require a C compiler when that is a problem.</p>

<p>Somewhere around version 3, this module was forked into <code>Cpanel::JSON::XS</code>, because its maintainer had serious trouble understanding JSON and insisted on a fork with many bugs &quot;fixed&quot; that weren&#39;t actually bugs, while spreading FUD about this module without actually giving any details on his accusations. You be the judge, but in my personal opinion, if you want quality, you will stay away from dangerous forks like that.</p>

<h1 id="BUGS">BUGS</h1>

<p>While the goal of this module is to be correct, that unfortunately does not mean it&#39;s bug-free, only that I think its design is bug-free. If you keep reporting bugs they will be fixed swiftly, though.</p>

<p>Please refrain from using rt.cpan.org or any other bug reporting service. I put the contact address into my modules for a reason.</p>

<h1 id="SEE-ALSO"><a id="SEE"></a>SEE ALSO</h1>

<p>The <i>json_xs</i> command line utility for quick experiments.</p>

<h1 id="AUTHOR">AUTHOR</h1>

<pre><code> Marc Lehmann &lt;schmorp@schmorp.de&gt;
 http://home.schmorp.de/</code></pre></div>

<div id="metacpan_install-instructions-dialog" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Module Install Instructions</h4>
      </div>
      <div class="modal-body">
        <p>To install JSON::XS, copy and paste the appropriate command in to your terminal.</p>
        <p><a href="https://metacpan.org/dist/App-cpanminus/view/bin/cpanm">cpanm</a></p>
        <pre><code>cpanm JSON::XS</code></pre>
        <p><a href="https://metacpan.org/pod/CPAN">CPAN shell</a></p>
        <pre><code>perl -MCPAN -e shell
install JSON::XS</code></pre>
        <p>For more information on module installation, please visit <a href="https://www.cpan.org/modules/INSTALL.html">the detailed CPAN module installation guide</a>.</p>
      </div>
      <div class="modal-footer">
        <a href="./JSON::XS.html#" data-dismiss="modal" class="btn">Close</a>
      </div>
    </div>
  </div>
</div>
          </main>
          <div class="content-pagination">
          </div>
        </div>
        <footer class="footer">
          <div class="footer-container">
            <div class="footer-social">
              <div class="footer-link footer-logo">
                <a href="https://metacpan.org/">
                  <img src="https://metacpan.org/static/images/metacpan-logo.svg" alt="MetaCPAN" />
                </a>
              </div>
              <a class="footer-social-link" href="https://github.com/metacpan">
                <i class="fab fa-github-square"></i>
              </a>
              <a class="footer-social-link" href="https://fosstodon.org/@metacpan">
                <i class="fab fa-mastodon"></i>
              </a>
            </div>
            <div class="footer-links">
              <div class="footer-link">
                  <a href="https://metacpan.org/about">About</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/sponsors">Sponsor</a>
              </div>
              <div class="footer-link">
                  <a href="https://grep.metacpan.org">grep::cpan</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/recent">Recent</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/faq">FAQ</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/tools">Tools</a>
              </div>
              <div class="footer-link">
                  <a href="https://fastapi.metacpan.org/">API</a>
              </div>
              <div class="footer-link">
                  <a href="https://www.perl.org/">Perl.org</a>
              </div>
            </div>
            <div class="footer-sponsors">
              <a class="footer-sponsor-link" target="_blank" href="https://www.bytemark.co.uk/" rel="noopener">
                <img class="footer-sponsor-bytemark" src="https://metacpan.org/static/images/sponsors/bytemark_logo.svg" alt="Bytemark logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.liquidweb.com/" rel="noopener">
                <img class="footer-sponsor-liquidweb" src="https://metacpan.org/static/images/sponsors/liquidweb_logo.png" alt="liquidweb logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://deriv.com/careers/" rel="noopener">
                <img class="footer-sponsor-deriv" src="https://metacpan.org/static/images/sponsors/deriv.svg" alt="Deriv logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://geocode.xyz" rel="noopener">
                <img class="footer-sponsor-geocode" src="https://metacpan.org/static/images/sponsors/geocodelogo.svg" alt="Geocode logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.fastly.com/" rel="noopener">
                <img class="footer-sponsor-fastly" src="https://metacpan.org/static/images/sponsors/fastly_logo.svg" alt="Fastly logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://opencagedata.com" rel="noopener">
                <img class="footer-sponsor-opencage" src="https://metacpan.org/static/images/sponsors/open-cage.svg" alt="OpenCage logo">
              </a>
            </div>
          </div>
        </footer>
        <div class="modal fade" tabindex="-1" role="dialog" id="metacpan_keyboard-shortcuts">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Keyboard Shortcuts</h4>
              </div>
              <div class="modal-body row">
<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Global</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>s</kbd>
        </td>
        <td>Focus search bar</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>?</kbd>
        </td>
        <td>Bring up this help dialog</td>
      </tr>
    </tbody>
  </table>

  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>GitHub</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>p</kbd>
        </td>
        <td>Go to pull requests</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>go to github issues (only if github is preferred repository)</td>
      </tr>
    </tbody>
  </table>
</div>

<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>POD</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>a</kbd>
        </td>
        <td>Go to author</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>c</kbd>
        </td>
        <td>Go to changes</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>Go to issues</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>d</kbd>
        </td>
        <td>Go to dist</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>r</kbd>
        </td>
        <td>Go to repository/SCM</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>s</kbd>
        </td>
        <td>Go to source</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>b</kbd>
        </td>
        <td>Go to file browse</td>
      </tr>

    </tbody>
  </table>
</div>

<div class="col-md-12">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Search terms</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><em>module:</em> (e.g. <a href="https://metacpan.org/search?q=module%3APlugin">module:Plugin</a>)</td>
      </tr>
      <tr>
        <td><em>distribution:</em> (e.g. <a href="https://metacpan.org/search?q=distribution%3ADancer+auth">distribution:Dancer auth</a>)</td>
      </tr>
      <tr>
        <td><em>author:</em> (e.g. <a href="https://metacpan.org/search?q=author%3ASONGMU+Redis">author:SONGMU Redis</a>)</td>
      </tr>
      <tr>
        <td><em>version:</em> (e.g. <a href="https://metacpan.org/search?q=version%3A1.00">version:1.00</a>)</td>
      </tr>
    </tbody>
  </table>
</div>
              </div>
              <div class="modal-footer"></div>
            </div>
          </div>
        </div>
    </body>
</html>
